智盟项目
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
962 B

  1. package db
  2. import (
  3. "fmt"
  4. "os"
  5. _ "github.com/go-sql-driver/mysql"
  6. "xorm.io/xorm"
  7. "xorm.io/xorm/log"
  8. "applet/app/cfg"
  9. )
  10. var ZhimengDb *xorm.Engine
  11. func InitZhimengDB(c *cfg.DBCfg) error {
  12. var err error
  13. if ZhimengDb, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4", c.User, c.Psw, c.Host, c.Name)); err != nil {
  14. return err
  15. }
  16. ZhimengDb.SetConnMaxLifetime(c.MaxLifetime)
  17. ZhimengDb.SetMaxOpenConns(c.MaxOpenConns)
  18. ZhimengDb.SetMaxIdleConns(c.MaxIdleConns)
  19. if err = Db.Ping(); err != nil {
  20. return err
  21. }
  22. if c.ShowLog {
  23. ZhimengDb.ShowSQL(true)
  24. ZhimengDb.Logger().SetLevel(0)
  25. f, err := os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777)
  26. if err != nil {
  27. os.RemoveAll(c.Path)
  28. if f, err = os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777); err != nil {
  29. return err
  30. }
  31. }
  32. logger := log.NewSimpleLogger(f)
  33. logger.ShowSQL(true)
  34. ZhimengDb.SetLogger(logger)
  35. }
  36. return nil
  37. }