Explorar el Código

update

master
dengbiao hace 2 días
padre
commit
05d64c6d92
Se han modificado 1 ficheros con 51 adiciones y 0 borrados
  1. +51
    -0
      src/db_back.go

+ 51
- 0
src/db_back.go Ver fichero

@@ -0,0 +1,51 @@
package db

import (
"fmt"
"os"

_ "github.com/go-sql-driver/mysql" //必须导入mysql驱动,否则会panic
"xorm.io/xorm"
"xorm.io/xorm/log"
)

type BackUpDBCfg struct {
Host string `yaml:"host"` //ip及端口
Name string `yaml:"name"` //库名
User string `yaml:"user"` //用户
Psw string `yaml:"psw"` //密码
ShowLog bool `yaml:"show_log"` //是否显示SQL语句
Path string `yaml:"path"` //日志文件存放路径
}

// 根据DB配置文件初始化数据库
func InitBackUpDB(c *BackUpDBCfg) (Db *xorm.Engine, err error) {
fmt.Println("db host::::", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4", c.User, c.Psw, c.Host, c.Name))
var (
f *os.File
)
//创建Orm引擎
if Db, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4", c.User, c.Psw, c.Host, c.Name)); err != nil {
return
}
if err = Db.Ping(); err != nil { //尝试ping数据库
return
}
if c.ShowLog { //根据配置文件设置日志
Db.ShowSQL(true) //设置是否打印sql
Db.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
}
}
logger := log.NewSimpleLogger(f)
logger.ShowSQL(true)
Db.SetLogger(logger)
}
return
}

Cargando…
Cancelar
Guardar