8/8/2025

gorm连接配置

var err error
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=ascii&parseTime=True&loc=Asia%%2FShanghai",
os.Getenv("MYSQL_USER"),
os.Getenv("MYSQL_PASSWD"),
os.Getenv("MYSQL_HOST"),
os.Getenv("MYSQL_DB"),
)

// 初始化 GORM 连接
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
// SkipDefaultTransaction: true,
})
if err != nil {
panic("failed to connect database")
}
sqlDB, err := db.DB()

// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
sqlDB.SetMaxIdleConns(50)

// SetMaxOpenConns sets the maximum number of open connections to the database.
sqlDB.SetMaxOpenConns(200)

// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
sqlDB.SetConnMaxLifetime(time.Minute * 3)

func main() {
// 设置东八区时区
loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
log.Fatal(err)
}

db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
	NowFunc: func() time.Time {
		return time.Now().In(loc)
	},
})
if err != nil {
	log.Fatal(err)
}

// 确认当前时间
var now time.Time
db.Raw("SELECT CURRENT_TIMESTAMP").Scan(&now)
log.Println("当前时间(东八区):", now)

}