|
- package db
-
- import (
- "fmt"
- "os"
-
- _ "github.com/go-sql-driver/mysql"
- "xorm.io/xorm"
- "xorm.io/xorm/log"
-
- "applet/app/cfg"
- )
-
- var ZhimengDb *xorm.Engine
-
- func InitZhimengDB(c *cfg.DBCfg) error {
- var err error
- 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 {
- return err
- }
- ZhimengDb.SetConnMaxLifetime(c.MaxLifetime)
- ZhimengDb.SetMaxOpenConns(c.MaxOpenConns)
- ZhimengDb.SetMaxIdleConns(c.MaxIdleConns)
- if err = Db.Ping(); err != nil {
- return err
- }
- if c.ShowLog {
- ZhimengDb.ShowSQL(true)
- ZhimengDb.Logger().SetLevel(0)
- f, err := os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777)
- if err != nil {
- os.RemoveAll(c.Path)
- if f, err = os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777); err != nil {
- return err
- }
- }
- logger := log.NewSimpleLogger(f)
- logger.ShowSQL(true)
- ZhimengDb.SetLogger(logger)
- }
- return nil
- }
|