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{}) data := TestData{} //插入一条数据 data = TestData{ LastLoginIp: "111", LastLoginTime: 222, Status: 333, CreateTime: 444, UpdateTime: 555, } if row, err := InsertOneTestData(&data); err != nil || row == 0 { fmt.Println(err, row) SimplePanic(err) return } //插入多条数据 //目前 gorm 并不支持批量插入这一功能,但已经被列入 v2.0 的计划里面了 } /* 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 InsertOneTestData(data *TestData) (int64, error) { db := dbClient.Create(data) return db.RowsAffected, db.Error } ~~~