| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- package db
- import (
- "encoding/hex"
- "fmt"
- "mtp2_if/config"
- "mtp2_if/logger"
- "mtp2_if/packet"
- "github.com/xormplus/core"
- "github.com/xormplus/xorm"
- "github.com/xormplus/xorm/log"
- )
- // MySQLEngine MySQL Engine
- var MySQLEngine *xorm.Engine
- // InitMySQLDbEngine 创建数据库驱动
- func InitMySQLDbEngine() error {
- host := config.SerCfg.GetMySQLHost()
- port := config.SerCfg.GetMySQLPort()
- dbname := config.SerCfg.GetMySQLDBName()
- username := config.SerCfg.GetMySQLUsername()
- password := config.SerCfg.GetMySQLPassword()
- // 尝试解密
- var dbUser []byte
- ciphertext, _ := hex.DecodeString(username)
- if len(ciphertext) > 8 {
- ciphertext = ciphertext[4 : len(ciphertext)-8]
- dbUser, _ = packet.Decrypt(ciphertext, packet.AESKey, true)
- if dbUser == nil {
- dbUser = []byte(username)
- }
- } else {
- dbUser = []byte(username)
- }
- var dbPwd []byte
- ciphertext, _ = hex.DecodeString(password)
- if len(ciphertext) > 8 {
- ciphertext = ciphertext[4 : len(ciphertext)-8]
- dbPwd, _ = packet.Decrypt(ciphertext, packet.AESKey, true)
- if dbPwd == nil {
- dbPwd = []byte(password)
- }
- } else {
- dbPwd = []byte(password)
- }
- dataSourceName := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8", string(dbUser), string(dbPwd), host, port, dbname)
- var err error
- MySQLEngine, err = xorm.NewEngine("mysql", dataSourceName)
- if err != nil {
- fmt.Println("create mysql engine failed:", err)
- return err
- }
- Engine.SetMaxIdleConns(10)
- Engine.SetMaxOpenConns(100)
- if config.SerCfg.GetDebugMode() {
- // 将SQL写到日志文件
- logger := log.NewSimpleLogger(logger.GetLogWriter())
- MySQLEngine.SetLogger(logger)
- // 将SQL打印到Console
- MySQLEngine.ShowSQL(true)
- MySQLEngine.SetTableMapper(core.SameMapper{})
- } else {
- MySQLEngine.ShowSQL(false)
- }
- return nil
- }
- // GetMySQLEngine GetMySQLEngine
- func GetMySQLEngine() *xorm.Engine {
- return MySQLEngine
- }
- // CloseMySQL CloseMySQL
- func CloseMySQL() {
- MySQLEngine.Close()
- }
|