💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
~~~ 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{} if ok, err := getOneTestData(&data); err != nil && !ok { SimplePanic(err) return } fmt.Println(data) } /* 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 getOneTestData(data *TestData) (bool, error) { db := dbClient.Model(data).First(&data, "1=1") return db.RecordNotFound(), db.Error } ~~~