mysq-gorm.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. "gorm.io/gorm/logger"
  8. "log"
  9. "gorm.io/driver/mysql"
  10. "gorm.io/gorm"
  11. )
  12. var db *gorm.DB
  13. // Setup 建立连接
  14. func InitMysqlGorm(user, passwd, addr, dbname, charset string, maxIdle, maxConn json.Number, logMode bool) *gorm.DB {
  15. args := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=%s&parseTime=True&loc=Local",
  16. user, passwd, addr, dbname, charset)
  17. fmt.Println("args", args)
  18. var err error
  19. db, err = gorm.Open(mysql.Open(args), &gorm.Config{})
  20. if err != nil {
  21. log.Fatal("open mysql connection failed. err: ", err)
  22. }
  23. if logMode{
  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. }*/