mysqldb.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package db
  2. import (
  3. "fmt"
  4. "mtp2_if/config"
  5. "mtp2_if/logger"
  6. "github.com/xormplus/core"
  7. "github.com/xormplus/xorm"
  8. "github.com/xormplus/xorm/log"
  9. )
  10. // MySQLEngine MySQL Engine
  11. var MySQLEngine *xorm.Engine
  12. // InitMySQLDbEngine 创建数据库驱动
  13. func InitMySQLDbEngine() error {
  14. host := config.SerCfg.GetMySQLHost()
  15. port := config.SerCfg.GetMySQLPort()
  16. dbname := config.SerCfg.GetMySQLDBName()
  17. username := config.SerCfg.GetMySQLUsername()
  18. password := config.SerCfg.GetMySQLPassword()
  19. dataSourceName := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8", username, password, host, port, dbname)
  20. var err error
  21. MySQLEngine, err = xorm.NewEngine("mysql", dataSourceName)
  22. if err != nil {
  23. fmt.Println("create mysql engine failed:", err)
  24. return err
  25. }
  26. Engine.SetMaxIdleConns(10)
  27. Engine.SetMaxOpenConns(100)
  28. if config.SerCfg.GetDebugMode() {
  29. // 将SQL写到日志文件
  30. logger := log.NewSimpleLogger(logger.GetLogWriter())
  31. MySQLEngine.SetLogger(logger)
  32. // 将SQL打印到Console
  33. MySQLEngine.ShowSQL(true)
  34. MySQLEngine.SetTableMapper(core.SameMapper{})
  35. } else {
  36. MySQLEngine.ShowSQL(false)
  37. }
  38. return nil
  39. }
  40. // GetMySQLEngine GetMySQLEngine
  41. func GetMySQLEngine() *xorm.Engine {
  42. return MySQLEngine
  43. }
  44. // CloseMySQL CloseMySQL
  45. func CloseMySQL() {
  46. MySQLEngine.Close()
  47. }