type Student struct {
Id int64 `gorm:"primary_key"`
Name string `gorm:"column:name"`
Age int `gorm:"column:age"`
}
func (Student) TableName() string {
return "student"
}
插入
s := Student{Name: "abc", Age: 17,}
err = db.Model(&Student{}).Create(&s).Error
更新
# 更新单列
err = db.Model(&Student{}).Where("id = ?", 4).UpdateColumn("age", 0).Error
# 不同于Updates方法,Save方法支持全字段更新,即使字段值是零值
s := Student{Id: 1, Name: "abc", Age: 17,}
s.Age = 0
err = db.Save(&s).Error
删除
# 根据主键删除
s := Student{Id: 1, Name: "abc", Age: 17,}
err = db.Delete(&s).Error
# 根据非主键条件删除
err = db.Delete(&Student{}, "name = ?", "abc").Error
查询
# 查询单条记录
var s1 Student
err = db.Model(&Student{}).Where("id = ?", 2).First(&s1).Error
# 查询多条记录
var s1 []Student
err = db.Model(&Student{}).Find(&s1).Error
# 查询某列
var age int
err = db.Model(&Student{}).Select("age").Where("id = ?", 2).Scan(&age).Error
# 计数
var count int64
err = db.Model(&Student{}).Count(&count).Error
标签:总结,err,crud,Age,db,Student,Error,Model,gorm From: https://www.cnblogs.com/WJQ2017/p/18644819