1.安装 Gin 和 Gorm
go get -u github.com/gin-gonic/gin
go get -u gorm.io/gorm
新建项目,main 函数import 他们的包
"github.com/gin-gonic/gin"
"gorm.io/driver/mysql"
"gorm.io/gorm"
2.连接MySQL
var DB *gorm.DB // 全局DB,方便后续扩展其他包调用
func initMySQL() (err error) {
dsn := "root:root@tcp(127.0.0.1:13306)/bubble?charset=utf8mb4&parseTime=True&loc=Local"
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
})
if err != nil {
return
}
return nil
}
dsn 处换成自己的 MySQL 配置信息。
高级配置:参考 https://gorm.io/zh_CN/docs/connecting_to_the_database.html
db, err := gorm.Open(mysql.New(mysql.Config{
DSN: "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local", // DSN data source name
DefaultStringSize: 256, // string 类型字段的默认长度
DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
SkipInitializeWithVersion: false, // 根据当前 MySQL 版本自动配置
}), &gorm.Config{
})
3.声明模型并绑定
type Todo struct {
ID int `json:"id"`
Title string `json:"title"`
Status bool `json:"status"`
}
如想在数据库表中增加 CreatedAt , UpdatedAt 和 DeletedAt 字段,可在 Todo 模型中引入 gorm.Model 字段:
type Todo struct {
gorm.Model
ID int `json:"id"`
Title string `json:"title"`
Status bool `json:"status"`
}
gorm.Model 定义如下:
type Model struct {
ID uint `gorm:"primary_key"`//primary_key:设置主键
CreatedAt time