|
@@ -1,54 +0,0 @@
|
|
-package c_db
|
|
|
|
-
|
|
|
|
-import (
|
|
|
|
- "dcl_dispatch_server/src/package/config/c_log"
|
|
|
|
- _ "github.com/go-sql-driver/mysql"
|
|
|
|
- "github.com/jmoiron/sqlx"
|
|
|
|
- "os"
|
|
|
|
-)
|
|
|
|
-
|
|
|
|
-var MysqlDb *sqlx.DB
|
|
|
|
-
|
|
|
|
-// InitSqlxMysql 初始化mysql连接
|
|
|
|
-// - charset 字符集 utf8、utf8mb4
|
|
|
|
-func InitSqlxMysql(username string, password string, ip string, port string, dbname string, charset string) {
|
|
|
|
- var err error
|
|
|
|
- // 连接数据库
|
|
|
|
- // - parseTime 是否将数据库中的时间类型字段解析为 Go 中的 time.Time 类型。
|
|
|
|
- // - loc 时间解析时使用的本地位置信息。通常设置为 "Local"。
|
|
|
|
- MysqlDb, err = sqlx.Open("mysql", username+":"+password+"@tcp("+ip+":"+port+")/"+dbname+"?charset="+charset+"&parseTime=True&loc=Local")
|
|
|
|
- if err != nil {
|
|
|
|
- c_log.GlobalLogger.Error("程序退出。mysql连接失败:", err)
|
|
|
|
- os.Exit(-1)
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- // 配置连接池
|
|
|
|
- MysqlDb.SetMaxOpenConns(10) // 设置最大打开连接数为 10
|
|
|
|
- MysqlDb.SetMaxIdleConns(5) // 设置最大空闲连接数为 5
|
|
|
|
- MysqlDb.SetConnMaxLifetime(0) // 设置连接的最大生存时间为 0(不限制)
|
|
|
|
- c_log.GlobalLogger.Info("mysql连接成功。")
|
|
|
|
-}
|
|
|
|
-
|
|
|
|
-func DoTx(sqlTemplate string, params []any) error {
|
|
|
|
- // 插入到数据库
|
|
|
|
- tx, err := MysqlDb.Beginx()
|
|
|
|
- if err != nil {
|
|
|
|
- c_log.GlobalLogger.Error("开启事务失败:", err)
|
|
|
|
- return err
|
|
|
|
- }
|
|
|
|
- // 2 在事务中执行操作
|
|
|
|
- _, err = tx.Exec(sqlTemplate, params...)
|
|
|
|
- if err != nil {
|
|
|
|
- c_log.GlobalLogger.Error("执行操作失败,回滚事务:", err)
|
|
|
|
- tx.Rollback()
|
|
|
|
- return err
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- // 如果所有操作成功,则提交事务
|
|
|
|
- err = tx.Commit()
|
|
|
|
- if err != nil {
|
|
|
|
- c_log.GlobalLogger.Error("提交事务失败:", err)
|
|
|
|
- return err
|
|
|
|
- }
|
|
|
|
- return nil
|
|
|
|
-}
|
|
|