gorm
用 go mod 管理模块
-
导包
import ( "time" "gorm.io/driver/mysql" gorm "gorm.io/gorm" )
-
创建数据库引擎
db, err := gorm.Open(mysql.Open(MYSQL_URL)) if err != nil { fmt.Println(err) }
-
定义模型结构体
// column 字段名 // type 字段类型 bool、int、uint、float、string、time、bytes // scale ,size 字段长度 size貌似不起作用 // default 默认值 // primaryKey 主键 // index ,uniqueIndex 索引,唯一索引 // unique 唯一约束 // not null 非空约束 // check 检查 // autoIncrement 自增长 autoIncrementIncrement 自增长的步长 // embedded 嵌套 embeddedPrefix 嵌套前缀 // autoCreateTime 自动生成创建时间如果增操作没有传值 // autoUpdateTime 自动生成更新时间如果更新操作没有传值 // comment 备注信息 type Class struct { ID uint64 `gorm:"Primarykey;autoIncrement"` Name string `gorm:"column:my_name;Type:string;scale:100"` CreatedAt time.Time // CreatedAt 会在创建时如果是空会自动创建当前时间 UpdatedAt time.Time `gorm:"autoCreateTime;autoUpdateTime"` // 更新也一样 Flag bool `gorm:"type:bool;default:1"` // bool在数据库是0或1 } type Student struct { gorm.Model // 嵌套gorm定义的基类 Name string Age uint8 C_id uint64 } // gorm提供了四种验证钩子函数 func (s *Student) BeforeCreate(tx *gorm.DB) error { if s.Age <= 18 { return errors.New("Student.BeforeCreate") } return nil }
-
设置自动迁移
db.AutoMigrate(&Class{ }) db.AutoMigrate(&Student{ })
-
增
// 相当于修改了结构体,数据库中会自动更新 c1 := &Class{ Name: "一年级一班", } db.Create(c1) db.Create(&Class{ Name: "一年级二班", }) // 指定字段新增 指定的字段是结构体重的字段,不是数据库的 db.Select("Name").Create(&Class{ Name: "三年二班"}) // 忽略指定字段新增 忽略的字段就算是定义了也会忽略 db.Omit("ID").Create(&Class{ Name: "三年三班", ID: 100}) // 批量插入 users := make([]Student, 100) for i := 0; i < 100; i++ { users[i] = Student{ Name: fmt.Sprintf("user_%d", i)<