ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
~~~ package main import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" "runtime" "time" ) var dbClient *gorm.DB func main() { dbAddress := "120.77.239.240:23306" dbName := "hmsc" dbUser := "test" dbPassword := "123456" connStr := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local", dbUser, dbPassword, dbAddress, dbName) //连接数据库 if db, err := gorm.Open("mysql", connStr); err != nil { SimplePanic(err) return } else { dbClient = db dbClient.DB().SetMaxIdleConns(1024) dbClient.DB().SetMaxOpenConns(1024) dbClient.DB().SetConnMaxLifetime(9 * time.Second) } //创建数据库表(如数据库表不存在则创建数据库表, 后续增加字段再次运行会添加上次, 后续删除字段再次运行不做处理) dbClient.AutoMigrate(TestData{}) //Remake: 如果用struct转map的方式, struct的字段都要填上去,不然会被当成零值更新 data := make(map[string]interface{}) data["LastLoginIp"] = "" data["LastLoginTime"] = 0 data["Status"] = 0 data["CreateTime"] = 0 data["CreateTime"] = 0 whereSql := "test_id = 2" if row, err := UpdateOneTestData(data, whereSql); err != nil || row == 0 { fmt.Println(err, row) SimplePanic(err) return } } /* primary_key 主键 unique_index 唯一 auto_increment 自增 */ type TestData struct { TestId int64 `gorm:"primary_key;unique_index;auto_increment"` LastLoginIp string LastLoginTime int64 Status int CreateTime int64 UpdateTime int64 `gorm:"-"` } func SimplePanic(err error) { if err != nil { _, file, line, _ := runtime.Caller(1) fmt.Println(file, line, err) runtime.Goexit() } } //看函数上写着Update 零值不更新, Updates 全部更新, 实际上传结构体时都没用, map都可以 func UpdateOneTestData(data map[string]interface{}, whereSql string) (int64, error) { db := dbClient.Model(TestData{}).Where(whereSql).Update(data) return db.RowsAffected, db.Error } ~~~