gorm更新
连接数据库并初始化
import (
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var db *gorm.DB
func init() {
dsn := "root:123456@tcp(127.0.0.1:3306)/golang_test?charset=utf8mb4&parseTime=True&loc=Local"
d, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Info)})
if err != nil {
panic("failed to connect database")
}
db = d
}
type User struct {
gorm.Model
Name string
Age int
Birthday time.Time
Active bool
}
func CreateTables() {
db.AutoMigrate(&User{})
}
func insert() {
user := User{
Name: "krien",
Age: 20,
Birthday: time.Now(),
Active: true,
}
db.Create(&user)
}
保存所有字段
Save会保存所有字段,即使字段是零值
func update() {
var user User
db.First(&user)
user.Name = "Krien"
user.Age = 21
db.Save(&user)
}
根据条件更新
func update2() {
db.Model(&User{}).Where("active = ?", true).Update("name", "Kiki")
}
Struct
func update3() {
// Struct
var user User
db.First(&user)
db.Model(&user).Updates(User{Name: "tom", Age: 18, Active: false}) // 结构体更新active不生效,map可以
}
Map
func update4() {
// Map
var user User
db.First(&user)
db.Model(&user).Updates(map[string]interface{}{"name": "cake", "age": 12, "active": false})
}