1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| func ConnMysql() *gorm.DB { checkDatabase() dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&collation=%s&%s", config.Conf.Mysql.Username, config.Conf.Mysql.Password, config.Conf.Mysql.Host, config.Conf.Mysql.Port, config.Conf.Mysql.Database, config.Conf.Mysql.Charset, config.Conf.Mysql.Collation, config.Conf.Mysql.Query, ) showDsn := fmt.Sprintf( "%s:******@tcp(%s:%d)/%s?charset=%s&collation=%s&%s", config.Conf.Mysql.Username, config.Conf.Mysql.Host, config.Conf.Mysql.Port, config.Conf.Mysql.Database, config.Conf.Mysql.Charset, config.Conf.Mysql.Collation, config.Conf.Mysql.Query, ) db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ DisableForeignKeyConstraintWhenMigrating: true, }) if err != nil { logger.Log.Panicf("初始化mysql数据库异常: %v", err) } if config.Conf.Mysql.LogMode { db.Debug() } logger.Log.Infof("初始化mysql数据库完成! dsn: %s", showDsn) return db }
func checkDatabase() { dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/?charset=%s&collation=%s&%s", config.Conf.Mysql.Username, config.Conf.Mysql.Password, config.Conf.Mysql.Host, config.Conf.Mysql.Port, config.Conf.Mysql.Charset, config.Conf.Mysql.Collation, config.Conf.Mysql.Query, ) db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ DisableForeignKeyConstraintWhenMigrating: true, }) if err != nil { logger.Log.Panicf("初始化mysql数据库异常: %v", err) } sqlDB, err := db.DB() if err != nil { logger.Log.Panicf("获取SQL DB失败: %v", err) } defer sqlDB.Close() createDBStatement := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", config.Conf.Mysql.Database) _, err = sqlDB.Exec(createDBStatement) if err != nil { logger.Log.Panicf("验证数据库信息失败: %v", err) } }
|