service/library/mysqldb/client.go

25 lines
612 B
Go
Raw Permalink Normal View History

2023-12-21 22:17:40 +08:00
package mysqldb
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"service/library/configcenter"
"service/library/logger"
)
func NewMysqlDB(cfg *configcenter.MysqlConfig, database string) (*sqlx.DB, error) {
dsn := fmt.Sprintf(
"%s:%s@(%s)/%s?charset=utf8&parseTime=true&timeout=%ds&readTimeout=%ds&writeTimeout=%ds",
cfg.Username, cfg.Password, cfg.Uri, database, cfg.TimeoutS, cfg.ReadTimeoutS, cfg.WriteTimeoutS,
)
db, err := sqlx.Open("mysql", dsn)
if err != nil {
logger.Error("NewMysqlDB fail, dsn: %v,err: %v", dsn, err)
return nil, err
}
return db, err
}