1
0
forked from lxh/go-wxhelper
go-wxhelper/client/mysql.go

39 lines
873 B
Go
Raw Permalink Normal View History

2023-09-21 17:33:59 +08:00
package client
import (
"go-wechat/config"
2023-09-21 17:33:59 +08:00
"gorm.io/driver/mysql"
"gorm.io/gorm"
2023-12-07 23:00:16 +08:00
"gorm.io/gorm/logger"
2023-09-21 17:33:59 +08:00
"log"
2023-12-08 11:41:59 +08:00
"os"
"strconv"
2023-09-21 17:33:59 +08:00
)
2023-12-08 11:41:59 +08:00
// MySQL MySQL客户端
2023-09-21 17:33:59 +08:00
var MySQL *gorm.DB
func InitMySQLClient() {
// 创建连接对象
mysqlConfig := mysql.Config{
DSN: config.Conf.MySQL.GetDSN(),
2023-09-21 17:33:59 +08:00
DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式
DontSupportRenameColumn: true, // 用 `change` 重命名列
}
2023-12-07 23:00:16 +08:00
// gorm 配置
2023-12-08 11:41:59 +08:00
gormConfig := gorm.Config{}
// 是否开启调试模式
if flag, _ := strconv.ParseBool(os.Getenv("GORM_DEBUG")); flag {
gormConfig.Logger = logger.Default.LogMode(logger.Info)
2023-12-07 23:00:16 +08:00
}
conn, err := gorm.Open(mysql.New(mysqlConfig), &gormConfig)
2023-09-21 17:33:59 +08:00
if err != nil {
log.Panicf("初始化MySQL连接失败, 错误信息: %v", err)
} else {
log.Println("MySQL连接成功")
}
MySQL = conn
}