Go MySQL
last modified October 30, 2026 Go 1.27
In this article we show how to work with MySQL and MariaDB from Go. The
examples use the database/sql package with the
go-sql-driver/mysql driver and perform the basic operations: a
version query, selecting rows, inserting, updating, deleting, transactions and
timeouts.
database/sql is a generic interface around SQL databases. It
manages a pool of connections, prepares statements and scans results, while the
driver translates the calls into the MySQL wire protocol. The driver is
installed as a normal module and registered by a blank import.
All examples were run with Go 1.27.0, driver v1.10.1 and MariaDB 11.4.13.
Starting the database
A container keeps the article self-contained and does not touch a local
installation. The mariadb:11.4 image creates the database and the
user from environment variables on the first start.
$ docker run -d --name golang-mysql \
-e MARIADB_ROOT_PASSWORD=root \
-e MARIADB_DATABASE=testdb \
-e MARIADB_USER=user7 \
-e MARIADB_PASSWORD='s$cret' \
-p 3307:3306 mariadb:11.4
The container publishes MariaDB on port 3307, because 3306 is often occupied by a local server. The schema below creates the table used by every example in the article.
DROP TABLE IF EXISTS cities;
CREATE TABLE cities(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
population INT
);
INSERT INTO cities(name, population) VALUES('Bratislava', 432000);
INSERT INTO cities(name, population) VALUES('Budapest', 1759000);
INSERT INTO cities(name, population) VALUES('Prague', 1280000);
INSERT INTO cities(name, population) VALUES('Warsaw', 1748000);
INSERT INTO cities(name, population) VALUES('Los Angeles', 3971000);
INSERT INTO cities(name, population) VALUES('New York', 8550000);
INSERT INTO cities(name, population) VALUES('Edinburgh', 464000);
INSERT INTO cities(name, population) VALUES('Berlin', 3671000);
The population column is nullable on purpose; one of the later
sections shows what a NULL value does to a plain int scan. The
table is loaded with the mariadb client inside the container.
$ docker exec -i golang-mysql mariadb -uuser7 -p's$cret' testdb < schema.sql
$ docker exec golang-mysql mariadb -uuser7 -p's$cret' testdb \
-e "SELECT COUNT(*) FROM cities;"
COUNT(*)
8
Installing the driver
The driver is a normal module. It pulls one more dependency,
filippo.io/edwards25519, which implements the curve used by the
newer authentication plugins.
$ go mod init com.zetcode/mysql
go: creating new go.mod: module com.zetcode/mysql
$ go get github.com/go-sql-driver/mysql
go: added filippo.io/edwards25519 v1.2.0
go: added github.com/go-sql-driver/mysql v1.10.1
$ cat go.mod
module com.zetcode/mysql
go 1.27.0
require (
filippo.io/edwards25519 v1.2.0 // indirect
github.com/go-sql-driver/mysql v1.10.1 // indirect
)
Both requirements carry the // indirect marker because no file
imports them yet. Running go mod tidy after the first program is
written marks the driver as a direct requirement; the exact commands are
described in the modules article.
Querying the server version
sql.Open validates the driver name and the data source name but
does not connect. Ping is the first call that actually reaches the
server, so it is the right place to catch a wrong password or a stopped
container.
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "user7:s$cret@tcp(127.0.0.1:3307)/testdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
if err := db.Ping(); err != nil {
log.Fatal(err)
}
var version string
err = db.QueryRow("SELECT VERSION()").Scan(&version)
if err != nil {
log.Fatal(err)
}
fmt.Println(version)
}
The blank import runs the init function of the driver, which
registers the name mysql with database/sql. The
defer comes after the error check, so a nil db is
never closed. QueryRow executes a statement that returns at most
one row, and Scan copies the column into the variable.
$ go run version.go 11.4.13-MariaDB-ubu2404
Selecting rows
Query returns *sql.Rows, which must be closed. The
loop calls Next and Scan, and a final
rows.Err check reports errors that interrupted the iteration.
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
type City struct {
ID int
Name string
Population int
}
func main() {
db, err := sql.Open("mysql", "user7:s$cret@tcp(127.0.0.1:3307)/testdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
rows, err := db.Query("SELECT id, name, population FROM cities ORDER BY id")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var city City
if err := rows.Scan(&city.ID, &city.Name, &city.Population); err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", city)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
}
The columns are listed explicitly instead of using SELECT *, so the
order of the Scan arguments cannot drift when the table changes.
%+v prints the field names together with the values, which makes
the mapping visible.
$ go run select_all.go
{ID:1 Name:Bratislava Population:432000}
{ID:2 Name:Budapest Population:1759000}
{ID:3 Name:Prague Population:1280000}
{ID:4 Name:Warsaw Population:1748000}
{ID:5 Name:Los Angeles Population:3971000}
{ID:6 Name:New York Population:8550000}
{ID:7 Name:Edinburgh Population:464000}
{ID:8 Name:Berlin Population:3671000}
Inserting a row
Exec runs a statement that returns no rows. The result has
LastInsertId for an auto-increment column and
RowsAffected for the number of changed rows.
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "user7:s$cret@tcp(127.0.0.1:3307)/testdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
res, err := db.Exec("INSERT INTO cities(name, population) VALUES (?, ?)",
"Moscow", 12506000)
if err != nil {
log.Fatal(err)
}
id, err := res.LastInsertId()
if err != nil {
log.Fatal(err)
}
n, err := res.RowsAffected()
if err != nil {
log.Fatal(err)
}
fmt.Printf("id=%d rows=%d\n", id, n)
}
The ? placeholders are filled with the arguments in order, which
keeps the SQL text constant and the values out of it. The returned id is the
value generated for the new row.
The id is 9 because the table already holds eight rows. Running the program a second time inserts another city and returns 10.
$ go run insert.go id=9 rows=1
Placeholders and sql.ErrNoRows
QueryRow accepts placeholders in the same way as
Exec. When no row matches, Scan returns
sql.ErrNoRows, which is a normal condition and not a failure of the
connection.
package main
import (
"database/sql"
"errors"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
type City struct {
ID int
Name string
Population int
}
func cityByID(db *sql.DB, id int) (City, error) {
var c City
err := db.QueryRow("SELECT id, name, population FROM cities WHERE id = ?", id).
Scan(&c.ID, &c.Name, &c.Population)
return c, err
}
func main() {
db, err := sql.Open("mysql", "user7:s$cret@tcp(127.0.0.1:3307)/testdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
city, err := cityByID(db, 9)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", city)
_, err = cityByID(db, 9999)
fmt.Println(errors.Is(err, sql.ErrNoRows), err)
}
The helper hides the statement text and the scan targets behind a typed
function. The second call shows the error for a missing id: the message is
short because ErrNoRows is a sentinel value that callers compare
with errors.Is.
$ go run prepared.go
{ID:9 Name:Moscow Population:12506000}
true sql: no rows in result set
Updating rows
An UPDATE goes through Exec as well.
RowsAffected reports how many rows matched and were changed; MySQL
counts only rows whose values actually differ.
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "user7:s$cret@tcp(127.0.0.1:3307)/testdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
res, err := db.Exec("UPDATE cities SET population = ? WHERE name = ?",
440000, "Bratislava")
if err != nil {
log.Fatal(err)
}
n, err := res.RowsAffected()
if err != nil {
log.Fatal(err)
}
fmt.Printf("updated %d row(s)\n", n)
}
The argument order follows the placeholders, not the order of the assignments
in the statement: 440000 goes to population and the
name to the WHERE clause. A statement that changes nothing still
succeeds, with a count of zero.
$ go run update.go updated 1 row(s)
NULL columns
A nullable column can hold NULL, which has no int
representation. Scanning it into a plain integer fails, and the message names
the column and the target type.
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "user7:s$cret@tcp(127.0.0.1:3307)/testdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
_, err = db.Exec("INSERT INTO cities(name, population) VALUES (?, NULL)",
"Vatican City")
if err != nil {
log.Fatal(err)
}
var population int
err = db.QueryRow("SELECT population FROM cities WHERE name = ?",
"Vatican City").Scan(&population)
fmt.Println(population, err)
var np sql.NullInt64
err = db.QueryRow("SELECT population FROM cities WHERE name = ?",
"Vatican City").Scan(&np)
fmt.Printf("%+v %v\n", np, err)
}
sql.NullInt64 has an Int64 field and a
Valid flag. The zero value of the group reports
Valid: false, which is how a program tells NULL apart from a real
zero. The NullString, NullFloat64,
NullBool and NullTime types follow the same pattern.
$ go run nullval.go
0 sql: Scan error on column index 0, name "population": converting NULL to int is unsupported
{Int64:0 Valid:false} <nil>
Driver errors
The driver returns *mysql.MySQLError for errors reported by the
server. Its Number field holds the MySQL error code, which is
stable across languages and clients, and Message the server text.
package main
import (
"database/sql"
"errors"
"fmt"
"log"
"github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "user7:s$cret@tcp(127.0.0.1:3307)/testdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
_, err = db.Exec("INSERT INTO cities(id, name, population) VALUES (?, ?, ?)",
1, "Bratislava", 432000)
var me *mysql.MySQLError
if errors.As(err, &me) {
fmt.Println("number:", me.Number)
fmt.Println("message:", me.Message)
}
}
The row with id 1 already exists, so the server rejects the insert. Checking
me.Number == 1062 is more robust than matching the message text,
which depends on the server version and on the language settings.
$ go run dup.go number: 1062 message: Duplicate entry '1' for key 'PRIMARY'
Transactions
A transaction groups statements so that they either all succeed or all fail.
Begin starts one, Commit makes the changes visible and
Rollback discards them.
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
func count(db *sql.DB) int {
var n int
if err := db.QueryRow("SELECT COUNT(*) FROM cities").Scan(&n); err != nil {
log.Fatal(err)
}
return n
}
func main() {
db, err := sql.Open("mysql", "user7:s$cret@tcp(127.0.0.1:3307)/testdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
tx, err := db.Begin()
if err != nil {
log.Fatal(err)
}
_, err = tx.Exec("INSERT INTO cities(name, population) VALUES (?, ?)",
"Oslo", 709000)
if err != nil {
tx.Rollback()
log.Fatal(err)
}
_, err = tx.Exec("INSERT INTO cities(id, name, population) VALUES (?, ?, ?)",
1, "Bratislava", 432000)
if err != nil {
fmt.Println("second insert failed:", err)
}
fmt.Println("count before rollback:", count(db))
if err := tx.Rollback(); err != nil {
log.Fatal(err)
}
fmt.Println("count after rollback:", count(db))
}
The first insert succeeds inside the transaction, the second one hits the
duplicate primary key. The count is taken through the pool, which uses another
connection, so it cannot see the uncommitted row: both counts are 10. A
Commit instead of the rollback would have made Oslo permanent and
raised the count to 11.
$ go run tx.go second insert failed: Error 1062 (23000): Duplicate entry '1' for key 'PRIMARY' count before rollback: 10 count after rollback: 10
Cancelling a query with a context
QueryRowContext and ExecContext take a
context.Context. When the context expires, the driver interrupts
the statement on the server and returns the context error.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"time"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "user7:s$cret@tcp(127.0.0.1:3307)/testdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
start := time.Now()
var n int
err = db.QueryRowContext(ctx, "SELECT SLEEP(3)").Scan(&n)
fmt.Println(err)
fmt.Printf("after %.1fs\n", time.Since(start).Seconds())
}
The statement would run for three seconds, but the context is cancelled after one. The elapsed time is measured around the call and is rounded to one decimal place.
$ go run timeout.go context deadline exceeded after 1.0s
Configuring the connection pool
sql.DB is a pool, not a single connection. Its size and the
lifetime of the connections are set once at startup, and Stats
reports what the pool is doing.
package main
import (
"database/sql"
"fmt"
"log"
"time"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "user7:s$cret@tcp(127.0.0.1:3307)/testdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.SetMaxOpenConns(4)
db.SetMaxIdleConns(4)
db.SetConnMaxLifetime(3 * time.Minute)
var n int
if err := db.QueryRow("SELECT 1").Scan(&n); err != nil {
log.Fatal(err)
}
s := db.Stats()
fmt.Printf("max=%d open=%d inUse=%d idle=%d waits=%d\n",
s.MaxOpenConnections, s.OpenConnections, s.InUse, s.Idle, s.WaitCount)
}
After one query the pool holds one open connection, which is idle again because
Scan released it. WaitCount stays at zero as long as
no goroutine had to wait for a free connection; it grows when more queries run
concurrently than SetMaxOpenConns allows.
$ go run pool.go max=4 open=1 inUse=0 idle=1 waits=0
Source
In this article we have connected to MariaDB from Go, queried and modified the
cities table, handled NULL values and driver errors, used a
transaction, cancelled a slow query with a context and configured the
connection pool.
Author
List all Go tutorials.