多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
~~~ 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{}) data := TestData{} //更新一条数据 data = TestData{ LastLoginIp: "222", LastLoginTime: 222, Status: 333, CreateTime: 444, UpdateTime: 555, } whereSql := "test_id = 1" 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() } } func UpdateOneTestData(data *TestData, whereSql string) (int64, error) { db := dbClient.Model(data).Where(whereSql).Update(data) return db.RowsAffected, db.Error } ~~~