init.go 891 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright 2019 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package databasev1
  4. import (
  5. "fmt"
  6. "log"
  7. "github.com/jinzhu/gorm"
  8. _ "github.com/jinzhu/gorm/dialects/mysql"
  9. )
  10. var db *gorm.DB
  11. // Setup 建立连接
  12. func Setup(user, passwd, addr, dbname, charset string, maxIdle, maxConn int, logMode bool) *gorm.DB {
  13. // 组装参数
  14. args := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=%s&parseTime=True&loc=Local",
  15. user, passwd, addr, dbname, charset)
  16. // 打开新连接
  17. var err error
  18. db, err = gorm.Open("mysql", args)
  19. if err != nil {
  20. log.Fatal("open mysql connection failed. err: ", err)
  21. }
  22. // 其他设置
  23. db.LogMode(logMode)
  24. db.DB().SetMaxIdleConns(maxIdle)
  25. db.DB().SetMaxOpenConns(maxConn)
  26. return db
  27. }
  28. // DB 获取连接
  29. func DB() *gorm.DB {
  30. return db
  31. }
  32. // Close 关闭连接
  33. func Close() {
  34. if db != nil {
  35. db.Close()
  36. }
  37. }