123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- // Copyright 2019 autocareai.com. All rights reserved.
- // Use of this source code is governed by autocareai.com.
- package clinit
- import (
- "encoding/json"
- "fmt"
- "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.Debug()
- //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()
- }
- }*/
|