12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- // Copyright 2019 getensh.com. All rights reserved.
- // Use of this source code is governed by getensh.com.
- package clinit
- import (
- "encoding/json"
- "fmt"
- "gorm.io/gorm/logger"
- "log"
- "gorm.io/driver/mysql"
- "gorm.io/gorm"
- )
- var db *gorm.DB
- // Setup 建立连接
- func InitMysqlGorm(user, passwd, addr, dbname, charset string, maxIdle, maxConn json.Number, logMode bool) *gorm.DB {
- args := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=%s&parseTime=True&loc=Local",
- user, passwd, addr, dbname, charset)
- fmt.Println("args", args)
- var err error
- db, err = gorm.Open(mysql.Open(args), &gorm.Config{})
- if err != nil {
- log.Fatal("open mysql connection failed. err: ", err)
- }
- if logMode{
- db.Logger.LogMode(logger.Info)
- }else{
- db.Logger.LogMode(logger.Error)
- }
- maxIdleInt, _ := maxIdle.Int64()
- maxConnInt, _ := maxConn.Int64()
- sqlDb ,err := db.DB()
- sqlDb.SetMaxIdleConns(int(maxIdleInt))
- sqlDb.SetMaxOpenConns(int(maxConnInt))
- // 其他设置
- //fmt.Println("log mode:", logMode)
- /*db.LogMode(logMode)
- db.DB().SetMaxIdleConns(maxIdle)
- db.DB().SetMaxOpenConns(maxConn)*/
- return db
- }
- // DB 获取连接
- func DB() *gorm.DB {
- return db
- }
- /*
- // Close 关闭连接
- func Close() {
- if db != nil {
- db.Close()
- }
- }*/
|