mysq-gorm.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package clinit
  4. import (
  5. "encoding/json"
  6. "fmt"
  7. "log"
  8. "gorm.io/driver/mysql"
  9. "gorm.io/gorm"
  10. )
  11. var db *gorm.DB
  12. // Setup 建立连接
  13. func InitMysqlGorm(user, passwd, addr, dbname, charset string, maxIdle, maxConn json.Number, logMode bool) *gorm.DB {
  14. args := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=%s&parseTime=True&loc=Local",
  15. user, passwd, addr, dbname, charset)
  16. fmt.Println("args", args)
  17. var err error
  18. db, err = gorm.Open(mysql.Open(args), &gorm.Config{})
  19. if err != nil {
  20. log.Fatal("open mysql connection failed. err: ", err)
  21. }
  22. if logMode {
  23. db.Debug()
  24. //db.Logger.LogMode(logger.Info)
  25. } else {
  26. //db.Logger.LogMode(logger.Error)
  27. }
  28. maxIdleInt, _ := maxIdle.Int64()
  29. maxConnInt, _ := maxConn.Int64()
  30. sqlDb, err := db.DB()
  31. sqlDb.SetMaxIdleConns(int(maxIdleInt))
  32. sqlDb.SetMaxOpenConns(int(maxConnInt))
  33. // 其他设置
  34. //fmt.Println("log mode:", logMode)
  35. /*db.LogMode(logMode)
  36. db.DB().SetMaxIdleConns(maxIdle)
  37. db.DB().SetMaxOpenConns(maxConn)*/
  38. return db
  39. }
  40. // DB 获取连接
  41. func DB() *gorm.DB {
  42. return db
  43. }
  44. /*
  45. // Close 关闭连接
  46. func Close() {
  47. if db != nil {
  48. db.Close()
  49. }
  50. }*/