How do I run migrations using database/sql with MySQL?

To run migrations using database/sql with MySQL in Go, you typically create a series of SQL scripts that can be executed sequentially. These scripts handle the creation and modification of your database schema as your application evolves.

Here’s a basic example of how you can achieve that:

package main import ( "database/sql" "fmt" "log" _ "github.com/go-sql-driver/mysql" ) func main() { // Open database connection db, err := sql.Open("mysql", "username:password@tcp(localhost:3306)/dbname") if err != nil { log.Fatal(err) } defer db.Close() // Migrations migrations := []string{ `CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL UNIQUE );`, `CREATE TABLE IF NOT EXISTS posts ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT, title VARCHAR(255) NOT NULL, content TEXT, FOREIGN KEY (user_id) REFERENCES users(id) );`, } // Execute migrations for _, migration := range migrations { _, err := db.Exec(migration) if err != nil { log.Fatalf("Failed to execute migration: %v", err) } fmt.Println("Migration executed successfully.") } }

database/sql MySQL Go migrations Go database migrations SQL migrations Go MySQL example