官方文档 已经很详细的对gorm的使用方法进行介绍了。
连接数据库
1 | args := "root:root1234@(localhost:3306)/gamedb?charset=utf8mb4&parseTime=True&loc=Local" |
操作数据库
查询表是否存在
db.HasTable(&user)
db.HasTable(&User{})
db.HasTable("users")
创建表
db.CreateTable(&user)
删除表
db.DropTable(&User{})
db.DropTable("user")
db.DropTableIfExist(&User{},"prodcuts")
//删除两张表
修改表
- 修改列
db.Model(&User).ModifyColumn("description","text")
//修改description列为text - 删除列
db.Model(&User{}).DropColumn("description")
操作表数据
创建数据
db.Create(&user)
查询数据
Where函数里面使用?作为拼接。1
2
3
4
5db.First(&user) // SELECT * FROM users ORDER BY id LIMIT 1;
db.Last(&user) // SELECT * FROM users ORDER BY id DESC LIMIT 1;
db.Find(&users) // SELECT * FROM users;
db.First(&user,10) // SELECT * FROM users WHERE id = 10
db.Where("name = ?","jinzhu").First(&user) // SELECT * FROM users WHERE name = 'jinzhu' limit 1;Struct和map作为查询条件1
2
3
4
5
6Where("name <> ?", "jinzhu")
Where("name in (?)", []string{"jinzhu", "jinzhu 2"})
Where("name LIKE ?", "%jin%")
Where("name = ? AND age >= ?", "jinzhu", "22")
Where("updated_at > ?", lastWeek)
Where("created_at BETWEEN ? AND ?", lastWeek, today)1
2
3
4
5
6
7
8
9
10
11// Struct
db.Where(&User{Name: "jinzhu", Age: 20}).First(&user)
//// SELECT * FROM users WHERE name = "jinzhu" AND age = 20 LIMIT 1;
// Map
db.Where(map[string]interface{}{"name": "jinzhu", "age": 20}).Find(&users)
//// SELECT * FROM users WHERE name = "jinzhu" AND age = 20;
// 主键的Slice
db.Where([]int64{20, 21, 22}).Find(&users)
//// SELECT * FROM users WHERE id IN (20, 21, 22);修改数据
删除数据
坑位
unsupported Scan, storing driver.Value type []uint8 into type *time.Time
解决办法:数据库连接使用parseTime=true
便可以解决