Go: go-sql-driver/mysql (MySQL)
Connects, creates a todo table if it does not exist, inserts a row and counts open rows. The code is the same against the original database and against MachSQL; only the address changes.
The only change
Section titled “The only change”MYSQL_DSN="app:${DB_PASSWORD}@tcp(old-mysql:3306)/app"MYSQL_DSN="app:${DB_PASSWORD}@tcp(machsql-host:3306)/app"Nothing else changes: not the code, not the driver, not its version, not the SQL.
Versions
Section titled “Versions”- Go 1.27
- go-sql-driver/mysql v1.10.1
go mod tidyexport MYSQL_DSN="app:${DB_PASSWORD}@tcp(machsql-host:3306)/app"go run .Expected output: inserted todo <id>, <n> open.
Source
Section titled “Source”The program as it is kept and tested in the Mach Database for PostgreSQL repository; highlighted lines read the connection setting.
// database/sql with go-sql-driver/mysql.package main
import ( "database/sql" "fmt" "os"
_ "github.com/go-sql-driver/mysql")
func main() { db, err := sql.Open("mysql", os.Getenv("MYSQL_DSN")) if err != nil { fail(err) } defer db.Close()
if _, err := db.Exec("CREATE TABLE IF NOT EXISTS todo (id BIGINT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(200) NOT NULL, done BOOLEAN NOT NULL DEFAULT FALSE)"); err != nil { fail(err) } res, err := db.Exec("INSERT INTO todo (title) VALUES (?)", "write the examples") if err != nil { fail(err) } id, err := res.LastInsertId() if err != nil { fail(err) } var open int64 if err := db.QueryRow("SELECT count(*) FROM todo WHERE NOT done").Scan(&open); err != nil { fail(err) } fmt.Printf("inserted todo %d, %d open\n", id, open)}
func fail(err error) { fmt.Fprintln(os.Stderr, err) os.Exit(1)}module example.com/machsql/go-mysql
go 1.27
require github.com/go-sql-driver/mysql v1.10.1