package db import ( "fmt" "os" "time" _ "github.com/go-sql-driver/mysql" //必须导入mysql驱动,否则会panic "xorm.io/xorm" "xorm.io/xorm/log" "applet/app/cfg" ) var DataDb *xorm.Engine //根据DB配置文件初始化数据库 func InitDataDB(c *cfg.DBCfg) error { var ( err error f *os.File ) //创建Orm引擎 if DataDb, 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 } DataDb.SetConnMaxLifetime(c.MaxLifetime * time.Second) //设置最长连接时间 DataDb.SetMaxOpenConns(c.MaxOpenConns) //设置最大打开连接数 DataDb.SetMaxIdleConns(c.MaxIdleConns) //设置连接池的空闲数大小 if err = DataDb.Ping(); err != nil { //尝试ping数据库 return err } if c.ShowLog { //根据配置文件设置日志 DataDb.ShowSQL(true) //设置是否打印sql DataDb.Logger().SetLevel(0) //设置日志等级 //修改日志文件存放路径文件名是%s.log path := fmt.Sprintf(c.Path, c.Name) f, err = os.OpenFile(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) DataDb.SetLogger(logger) } return nil }