优惠券额度包
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.

db.go 2.4 KiB

2 years ago
2 years ago
2 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package db
  2. import (
  3. "code.fnuoos.com/go_rely_warehouse/zyos_go_coupon.git/md"
  4. "database/sql"
  5. "fmt"
  6. _ "github.com/go-sql-driver/mysql" //必须导入mysql驱动,否则会panic
  7. "time"
  8. "xorm.io/xorm"
  9. )
  10. var Db *xorm.Engine
  11. //根据DB配置文件初始化数据库
  12. func InitDB(c *md.DBCfg) error {
  13. var (
  14. err error
  15. //f *os.File
  16. )
  17. //创建Orm引擎
  18. 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 {
  19. return err
  20. }
  21. Db.SetConnMaxLifetime(c.MaxLifetime * time.Second) //设置最长连接时间
  22. Db.SetMaxOpenConns(c.MaxOpenConns) //设置最大打开连接数
  23. Db.SetMaxIdleConns(c.MaxIdleConns) //设置连接池的空闲数大小
  24. if err = Db.Ping(); err != nil { //尝试ping数据库
  25. return err
  26. }
  27. //if c.ShowLog { //根据配置文件设置日志
  28. // Db.ShowSQL(true) //设置是否打印sql
  29. // Db.Logger().SetLevel(0) //设置日志等级
  30. // //修改日志文件存放路径文件名是%s.log
  31. // path := fmt.Sprintf(c.Path, c.Name)
  32. // f, err = os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777)
  33. // if err != nil {
  34. // os.RemoveAll(c.Path)
  35. // if f, err = os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777); err != nil {
  36. // return err
  37. // }
  38. // }
  39. // logger := log.NewSimpleLogger(f)
  40. // logger.ShowSQL(true)
  41. // Db.SetLogger(logger)
  42. //}
  43. return nil
  44. }
  45. /********************************************* 公用方法 *********************************************/
  46. // QueryNativeString 查询原生sql
  47. func QueryNativeString(Db *xorm.Engine, sql string, args ...interface{}) ([]map[string]string, error) {
  48. results, err := Db.SQL(sql, args...).QueryString()
  49. return results, err
  50. }
  51. // UpdateComm common update
  52. func UpdateComm(Db *xorm.Engine, id interface{}, model interface{}) (int64, error) {
  53. row, err := Db.ID(id).Update(model)
  54. return row, err
  55. }
  56. // InsertComm common insert
  57. func InsertComm(Db *xorm.Engine, model interface{}) (int64, error) {
  58. row, err := Db.InsertOne(model)
  59. return row, err
  60. }
  61. // InsertCommWithSession common insert
  62. func InsertCommWithSession(session *xorm.Session, model interface{}) (int64, error) {
  63. row, err := session.InsertOne(model)
  64. return row, err
  65. }
  66. // ExecuteOriginalSql 执行原生sql
  67. func ExecuteOriginalSql(session *xorm.Session, sql string) (sql.Result, error) {
  68. result, err := session.Exec(sql)
  69. if err != nil {
  70. return nil, err
  71. }
  72. return result, nil
  73. }