commit
633297bc64
@ -0,0 +1,8 @@
|
||||
module git.oa00.com/go/mysql
|
||||
|
||||
go 1.16
|
||||
|
||||
require (
|
||||
gorm.io/driver/mysql v1.0.5
|
||||
gorm.io/gorm v1.21.8
|
||||
)
|
@ -0,0 +1,12 @@
|
||||
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
|
||||
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jinzhu/now v1.1.2 h1:eVKgfIdy9b6zbWBMgFpfDPoAMifwSZagU9HmEU6zgiI=
|
||||
github.com/jinzhu/now v1.1.2/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
gorm.io/driver/mysql v1.0.5 h1:WAAmvLK2rG0tCOqrf5XcLi2QUwugd4rcVJ/W3aoon9o=
|
||||
gorm.io/driver/mysql v1.0.5/go.mod h1:N1OIhHAIhx5SunkMGqWbGFVeh4yTNWKmMo1GOAsohLI=
|
||||
gorm.io/gorm v1.21.3/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
|
||||
gorm.io/gorm v1.21.8 h1:2CEwZSzogdhsKPlJ9OvBKTdlWIpELXb6HbfLfMNhSYI=
|
||||
gorm.io/gorm v1.21.8/go.mod h1:F+OptMscr0P2F2qU97WT1WimdH9GaQPoDW7AYd5i2Y0=
|
@ -0,0 +1,61 @@
|
||||
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
|
||||
}
|
||||
|
||||
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 Db, err = gorm.Open(mysql.New(mysqlConfig), &gorm.Config{
|
||||
NamingStrategy: schema.NamingStrategy{
|
||||
TablePrefix: dbConfig.Prefix, // 表名前缀
|
||||
SingularTable: !dbConfig.SingularTable, // 使用单数表名
|
||||
},
|
||||
Logger: logger.New(
|
||||
log.New(os.Stdout, "\r\n", log.LstdFlags),
|
||||
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
|
||||
}
|
||||
}
|
Loading…
Reference in new issue