工作中服务端使用go开发的,需要连接mysql ,基于gorm,经过稳定运行,记录一下连接mysql的代码吧

var _db *gorm.DB

func GetDB() *gorm.DB{
	return _db
}
func MySqlConn(dbUser string, dbPassword string, dbHost string, dbPort string, dbName string,
	timeout string, maxOpenConnection int, maxIdleConnection int, dbDebug bool) (bool,error){
	var err error
	var dialector gorm.Dialector
	var conn *gorm.DB
	dbUri := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Asia%%2fShanghai&timeout=%ss", dbUser, dbPassword, dbHost, dbPort, dbName,timeout)
	dialector = mysql.New(mysql.Config{
		DSN:                       dbUri, // data source name
		DefaultStringSize:         256,   // default size for string fields
		DisableDatetimePrecision:  true,  // disable datetime precision, which not supported before MySQL 5.6
		DontSupportRenameIndex:    true,  // drop & create when rename index, rename index not supported before MySQL 5.7, MariaDB
		DontSupportRenameColumn:   true,  // `change` when rename column, rename column not supported before MySQL 8, MariaDB
		SkipInitializeWithVersion: false, // auto configure based on currently MySQL version
	})
	if dbDebug {
		conn, err = gorm.Open(dialector, &gorm.Config{
			DisableForeignKeyConstraintWhenMigrating: true,
			Logger: logger.Default.LogMode(logger.Info),
		})
	}else {
		conn, err = gorm.Open(dialector, &gorm.Config{
			DisableForeignKeyConstraintWhenMigrating: true,
			Logger: logger.Default.LogMode(logger.Error),
		})
	}

	if err != nil {
		panic(err.Error())
	}
	sqlDB, err := conn.DB()
	if err != nil {
		panic("connect db server failed.")
	}
	sqlDB.SetMaxIdleConns(maxIdleConnection)                   // SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxOpenConns(maxOpenConnection)                  // SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetConnMaxLifetime(time.Second * 30) // SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	_db = conn
	return true,nil
}

更多推荐