picgo/corelib/msyql.go
2024-07-12 20:32:33 +08:00

50 lines
1.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package corelib
import (
"database/sql"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
"picgo/configs"
"time"
)
var (
DbMysql *gorm.DB
)
// NewMysql 创建数据库连接
func NewMysql() {
var (
err error
db *gorm.DB
sqlDB *sql.DB
dsn string
)
dsn = configs.Settings.Mysql.MysqlDNS
if db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
// 配置日志级别打印出所有的sql
Logger: logger.Default.LogMode(logger.Info),
NamingStrategy: schema.NamingStrategy{
//TablePrefix: configs.Setting.TablePrefix, // 表前缀
SingularTable: true, // 设置全局表名禁用复数
},
}); err != nil {
Logger.Panicln("数据库连接失败: ", err)
}
if sqlDB, err = db.DB(); err != nil {
Logger.Panicln("数据库连接失败: ", err)
}
// SetMaxIdleConns 设置空闲连接池中连接的最大数量
sqlDB.SetMaxIdleConns(configs.Settings.Mysql.MaxIdleConns)
// SetMaxOpenConns 设置打开数据库连接的最大数量。
sqlDB.SetMaxOpenConns(configs.Settings.Mysql.MaxOpenConns)
// SetConnMaxLifetime 设置了连接可复用的最大时间。
sqlDB.SetConnMaxLifetime(time.Hour)
DbMysql = db
}