1.1 安装依赖
这里以mysql为例,导入mysql驱动
go get -u gorm.io/gormgo get gorm.io/driver/mysql
1.2 创建数据库
CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(255) NOT NULL COMMENT '昵称',`openid` varchar(64) NOT NULL COMMENT '微信id',PRIMARY KEY (`id`),UNIQUE KEY `UK_openid` (`openid`) USING BTREE COMMENT 'openid不可重复') ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
1.2 编写配置文件
这里使用viper来管理配置文件
go get github.com/spf13/viper
编写配置文件
config/application.yml
server:port: 8080datasource:drivername: mysqlhost: 127.0.0.1username: rootpassword: yourpassworddatabase: g-study
初始化viper
config/config.go
package configimport ("github.com/spf13/viper""os")func Setup() {workDir, _ := os.Getwd()viper.AddConfigPath(workDir + "/config/")viper.SetConfigType("yml")viper.SetConfigName("application")err := viper.ReadInConfig()if err != nil {panic(err)}}
main.go
package mainimport ("fmt""github.com/spf13/viper""study-everyday/config")func init() {config.Setup()}func main() {fmt.Println(viper.GetString("datasource.driver-name"))}
mysql
一切准备就绪,那么开始我们的gorm之旅叭。
