安装
go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlite
gorm.Model模型
type Model struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
}
- gorm约定默认将
ID
作为主键 - 我们可以将Model模型嵌入结构体中
type user struct {
gorm.Model
Name string
}
字段标签
- 声明 model 时,tag 是可选的,GORM 支持以下 tag: tag 名大小写不敏感,但建议使用 camelCase 风格
type user struct {
ID uint `gorm:"primaryKey"`
Name string
}
连接到mysql数据库
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func main() {
// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
}
迁移
AutoMigrate()用于自动迁移您的 schema,保持您的 schema 是最新的。
db.AutoMigrate(&User{})
db.Migrator().CurrentDatabase() //返回当前使用的数据库名
其他迁移
- GORM 的 AutoMigrate 适用于大多数的迁移,如果您需要更加个性化的迁移工具 ,GORM 提供的一个通用数据库接口可能对您有帮助。
// returns `*sql.DB`
db.DB()
创建记录
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type user struct {
ID uint `gorm:"primaryKey"`
Name string
Age uint
}
func main() {
dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
fmt.Println("err", err)
}
db.AutoMigrate(&user{})
u := user{
Name: "mac",
Age: 18,
}
result := db.Create(&u)
fmt.Println(u.ID) //返回ID
fmt.Println(result.Error) //返回error
fmt.Println(result.RowsAffected) //返回插入记录的条数
}
用指定字段插入
db.Select("Name").Create(&u) //只插入Name字段
db.Omit("Name", ).Create(&u) //插入除Name以外的其他字段
批量插入
var users = []User{{Name: "person1"}, {Name: "person2"}, {Name: "person3"}}
db.Create(&users)
使用map插入
db.Model(&User{}).Create(map[string]interface{}{
"Name": "person", "Age": 18,
})
// batch insert from `[]map[string]interface{}{}`
db.Model(&User{}).Create([]map[string]interface{}{
{"Name": "person1", "Age": 18},
{"Name": "person2", "Age": 20},
})
查询
// 获取第一条记录(主键升序)
db.First(&user)
// SELECT * FROM users ORDER BY id LIMIT 1;
// 获取一条记录,没有指定排序字段
db.Take(&user)
// SELECT * FROM users LIMIT 1;
// 获取最后一条记录(主键降序)
db.Last(&user)
// SELECT * FROM users ORDER BY id DESC LIMIT 1;
//获取所有记录
db.Find(&user)
//SELECT * FROM users
用主键检索
db.First(&user, 10)
// SELECT * FROM users WHERE id = 10;
db.First(&user, "10")
// SELECT * FROM users WHERE id = 10;
db.Find(&users, []int{1,2,3})
// SELECT * FROM users WHERE id IN (1,2,3);
更新
保存所有字段
db.First(&user)
user.Name = "person"
user.Age = 18
db.Save(&user)
保存非零字段
db.Where("id=?",1).Update("name","jerry")
删除
db.Delete(&user)
db.Where("name=?", "jerry").Delete(&user{})
根据主键删除
db.Delete(&User{}, 10)
// DELETE FROM users WHERE id = 10;
db.Delete(&User{}, "10")
// DELETE FROM users WHERE id = 10;
db.Delete(&users, []int{1,2,3})
// DELETE FROM users WHERE id IN (1,2,3);
执行原生SQL
raw()+scan()
type Result struct {
ID int
Name string
Age int
}
var result Result
db.Raw("SELECT id, name, age FROM users WHERE name = ?", 3).Scan(&result)
db.Raw("SELECT id, name, age FROM users WHERE name = ?", 3).Scan(&result)
var age int
db.Raw("SELECT SUM(age) FROM users WHERE role = ?", "admin").Scan(&age)
var users []User
db.Raw("UPDATE users SET name = ? WHERE age = ? RETURNING id, name", "person", 20).Scan(&users)
Exec() 原生SQL
db.Exec("DROP TABLE users")
db.Exec("UPDATE orders SET shipped_at = ? WHERE id IN ?", time.Now(), []int64{1, 2, 3})
// Exec with SQL Expression
db.Exec("UPDATE users SET money = ? WHERE name = ?", gorm.Expr("money * ? + ?", 10000, 1), "person")