You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mysql/mysql.go

66 lines
1.5 KiB

package mysql
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
"log"
"os"
)
var Db *gorm.DB
type DbConfig struct {
Username string
Password string
Host string
Port int
Prefix string
Extend string
SingularTable bool
LogColorful bool
LogLevel LogLevel
MaxIdleConns int
MaxOpenConns int
DbName string
Logger logger.Writer
}
type LogLevel = logger.LogLevel
// InitMysql @Title 初始化Mysql数据库
func InitMysql(dbConfig *DbConfig) (err error) {
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", dbConfig.Username, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.DbName)
if dbConfig.Extend != "" {
dsn += "?" + dbConfig.Extend
}
mysqlConfig := mysql.Config{
DSN: dsn, // DSN data source name
}
if dbConfig.Logger == nil {
dbConfig.Logger = log.New(os.Stdout, "\r\n", log.LstdFlags)
}
if Db, err = gorm.Open(mysql.New(mysqlConfig), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
TablePrefix: dbConfig.Prefix, // 表名前缀
SingularTable: !dbConfig.SingularTable, // 使用单数表名
},
Logger: logger.New(
dbConfig.Logger,
logger.Config{
Colorful: !dbConfig.LogColorful,
LogLevel: dbConfig.LogLevel, // Log level
},
),
}); err != nil {
return
} else {
sqlDB, _ := Db.DB()
sqlDB.SetMaxIdleConns(dbConfig.MaxIdleConns)
sqlDB.SetMaxOpenConns(dbConfig.MaxOpenConns)
return
}
}