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.
 
 
 

52 lines
1.5 KiB

  1. package db
  2. import (
  3. "fmt"
  4. "os"
  5. _ "github.com/go-sql-driver/mysql" //必须导入mysql驱动,否则会panic
  6. "xorm.io/xorm"
  7. "xorm.io/xorm/log"
  8. )
  9. type BackUpDBCfg struct {
  10. Host string `yaml:"host"` //ip及端口
  11. Name string `yaml:"name"` //库名
  12. User string `yaml:"user"` //用户
  13. Psw string `yaml:"psw"` //密码
  14. ShowLog bool `yaml:"show_log"` //是否显示SQL语句
  15. Path string `yaml:"path"` //日志文件存放路径
  16. }
  17. // 根据DB配置文件初始化数据库
  18. func InitBackUpDB(c *BackUpDBCfg) (Db *xorm.Engine, err error) {
  19. fmt.Println("db host::::", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4", c.User, c.Psw, c.Host, c.Name))
  20. var (
  21. f *os.File
  22. )
  23. //创建Orm引擎
  24. 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 {
  25. return
  26. }
  27. if err = Db.Ping(); err != nil { //尝试ping数据库
  28. return
  29. }
  30. if c.ShowLog { //根据配置文件设置日志
  31. Db.ShowSQL(true) //设置是否打印sql
  32. Db.Logger().SetLevel(0) //设置日志等级
  33. //修改日志文件存放路径文件名是%s.log
  34. path := fmt.Sprintf(c.Path, c.Name)
  35. f, err = os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777)
  36. if err != nil {
  37. os.RemoveAll(c.Path)
  38. if f, err = os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777); err != nil {
  39. return
  40. }
  41. }
  42. logger := log.NewSimpleLogger(f)
  43. logger.ShowSQL(true)
  44. Db.SetLogger(logger)
  45. }
  46. return
  47. }