package global import ( "fmt" "gorm.io/driver/mysql" "gorm.io/gorm" "gorm.io/gorm/logger" . "goweb/config" "log" "os" "time" ) // InitMySQLClient 初始化MySQL连接 func InitMySQLClient() { // 初始化MySQL配置 InitMySQLConfig() newLogger := logger.New( log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer logger.Config{ SlowThreshold: time.Second, // Slow SQL threshold LogLevel: logger.Info, // Log level Colorful: true, // Disable color }, ) url := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", MySQLConfig.Username, MySQLConfig.Password, MySQLConfig.Host, MySQLConfig.Port, MySQLConfig.DbName) conn, err := gorm.Open(mysql.Open(url), &gorm.Config{Logger: newLogger}) if err != nil { Log.Panicf("初始化MySQL连接失败, 错误信息: %v", err) } MySQLConn = conn }