导入需要使用到的库,初始化的代码如下 func InitDB() *gorm.DB { newLogger := logger.New( log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{ SlowThreshold: time.Second, // 慢SQL阈值 LogLevel: logger.Info, // 级别 Colorful: true, }, ) hostname := "xxx" database := "xxx" user := "xxx" password := "xxx" dsn := fmt.Sprintf("%s:%s@tcp(%s)/", user, password, hostname) db, err := sql.Open("mysql", dsn) if err != nil { panic("failed to connect to MySQL server, err: " + err.Error()) } // Step 2: Create the database (if it does not exist) _, err = db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s;", database)) if err != nil { panic("failed to create database, err: " + err.Error()) } // Don't forget to close the connection when you're done db.Close() // Step 3: Connect to the newly created database using Gorm dsn = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local", user, password, hostname, database) gormDB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: newLogger}) if err != nil { panic("failed to connect to database, err: " + err.Error()) } fmt.Println("Successfully connected to database", database) return gormDB }