github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/toolbar/common/db.go (about)

     1  package common
     2  
     3  import (
     4  	"fmt"
     5  
     6  	_ "github.com/go-sql-driver/mysql"
     7  	"github.com/jinzhu/gorm"
     8  
     9  	"github.com/bytom/bytom/errors"
    10  )
    11  
    12  func NewMySQLDB(cfg MySQLConfig) (*gorm.DB, error) {
    13  	dsnTemplate := "%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=true&loc=Local"
    14  	dsn := fmt.Sprintf(dsnTemplate, cfg.Connection.Username, cfg.Connection.Password, cfg.Connection.Host, cfg.Connection.Port, cfg.Connection.DbName)
    15  	db, err := gorm.Open("mysql", dsn)
    16  	if err != nil {
    17  		return nil, errors.Wrap(err, "open db cluster")
    18  	}
    19  
    20  	db.LogMode(cfg.LogMode)
    21  	if err = db.DB().Ping(); err != nil {
    22  		return nil, errors.Wrap(err, "ping db")
    23  	}
    24  
    25  	return db, nil
    26  }