c_sqlx_config.go 1.1 KB

123456789101112131415161718192021222324252627282930
  1. package c_db
  2. import (
  3. "cicv-data-closedloop/common/config/c_log"
  4. _ "github.com/go-sql-driver/mysql"
  5. "github.com/jmoiron/sqlx"
  6. "os"
  7. )
  8. var MysqlDb *sqlx.DB
  9. // InitSqlxMysql 初始化mysql连接
  10. // - charset 字符集 utf8、utf8mb4
  11. func InitSqlxMysql(username string, password string, ip string, port string, dbname string, charset string) {
  12. var err error
  13. // 连接数据库
  14. // - parseTime 是否将数据库中的时间类型字段解析为 Go 中的 time.Time 类型。
  15. // - loc 时间解析时使用的本地位置信息。通常设置为 "Local"。
  16. MysqlDb, err = sqlx.Open("mysql", username+":"+password+"@tcp("+ip+":"+port+")/"+dbname+"?charset="+charset+"&parseTime=True&loc=Local")
  17. if err != nil {
  18. c_log.GlobalLogger.Error("程序退出。mysql连接失败:", err)
  19. os.Exit(-1)
  20. }
  21. // 配置连接池
  22. MysqlDb.SetMaxOpenConns(10) // 设置最大打开连接数为 10
  23. MysqlDb.SetMaxIdleConns(5) // 设置最大空闲连接数为 5
  24. MysqlDb.SetConnMaxLifetime(0) // 设置连接的最大生存时间为 0(不限制)
  25. c_log.GlobalLogger.Info("mysql连接成功。")
  26. }