mysqldb.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package db
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "mtp2_if/config"
  6. "mtp2_if/logger"
  7. "mtp2_if/packet"
  8. "github.com/xormplus/core"
  9. "github.com/xormplus/xorm"
  10. "github.com/xormplus/xorm/log"
  11. )
  12. // MySQLEngine MySQL Engine
  13. var MySQLEngine *xorm.Engine
  14. // InitMySQLDbEngine 创建数据库驱动
  15. func InitMySQLDbEngine() error {
  16. host := config.SerCfg.GetMySQLHost()
  17. port := config.SerCfg.GetMySQLPort()
  18. dbname := config.SerCfg.GetMySQLDBName()
  19. username := config.SerCfg.GetMySQLUsername()
  20. password := config.SerCfg.GetMySQLPassword()
  21. // 尝试解密
  22. var dbUser []byte
  23. ciphertext, _ := hex.DecodeString(username)
  24. if len(ciphertext) > 8 {
  25. ciphertext = ciphertext[4 : len(ciphertext)-8]
  26. dbUser, _ = packet.Decrypt(ciphertext, packet.AESKey, true)
  27. if dbUser == nil {
  28. dbUser = []byte(username)
  29. }
  30. } else {
  31. dbUser = []byte(username)
  32. }
  33. var dbPwd []byte
  34. ciphertext, _ = hex.DecodeString(password)
  35. if len(ciphertext) > 8 {
  36. ciphertext = ciphertext[4 : len(ciphertext)-8]
  37. dbPwd, _ = packet.Decrypt(ciphertext, packet.AESKey, true)
  38. if dbPwd == nil {
  39. dbPwd = []byte(password)
  40. }
  41. } else {
  42. dbPwd = []byte(password)
  43. }
  44. dataSourceName := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8", string(dbUser), string(dbPwd), host, port, dbname)
  45. var err error
  46. MySQLEngine, err = xorm.NewEngine("mysql", dataSourceName)
  47. if err != nil {
  48. fmt.Println("create mysql engine failed:", err)
  49. return err
  50. }
  51. Engine.SetMaxIdleConns(10)
  52. Engine.SetMaxOpenConns(100)
  53. if config.SerCfg.GetDebugMode() {
  54. // 将SQL写到日志文件
  55. logger := log.NewSimpleLogger(logger.GetLogWriter())
  56. MySQLEngine.SetLogger(logger)
  57. // 将SQL打印到Console
  58. MySQLEngine.ShowSQL(true)
  59. MySQLEngine.SetTableMapper(core.SameMapper{})
  60. } else {
  61. MySQLEngine.ShowSQL(false)
  62. }
  63. return nil
  64. }
  65. // GetMySQLEngine GetMySQLEngine
  66. func GetMySQLEngine() *xorm.Engine {
  67. return MySQLEngine
  68. }
  69. // CloseMySQL CloseMySQL
  70. func CloseMySQL() {
  71. MySQLEngine.Close()
  72. }