支付模块
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

85 líneas
2.4 KiB

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