Go Database Tutorial with database/sql

Updated 5 min read
Go Database featured image: cards for Exec, Query and transactions

Go database access starts with the database/sql package, which ships with the standard library. In this post, you will open a connection, create a table, insert rows, read them back and use a transaction. Each step comes with code that you can copy and run.

In the last lesson, the Go REST API tutorial stored books in a map, so the data vanished on restart. A database fixes that. You will also check errors at every step, just like in error handling in Go for beginners.

What Is a Go Database Driver?

To begin with, database/sql is a common interface. It knows how to run queries, but it does not know how to talk to a specific database. A driver fills that gap. For example, there are drivers for SQLite, PostgreSQL and MySQL.

Think of database/sql as a universal TV remote. The buttons stay the same, but you pair it with a different TV. In this post, we use SQLite through the pure Go driver modernc.org/sqlite, because it needs no extra setup.

go get modernc.org/sqlite

Opening a Go Database Connection

import (
	"database/sql"
	"log"

	_ "modernc.org/sqlite"
)

db, err := sql.Open("sqlite", "app.db")
if err != nil {
	log.Fatal(err)
}
defer db.Close()

if err := db.Ping(); err != nil {
	log.Fatal(err)
}

The blank import _ runs the driver’s setup code, which registers the name “sqlite”. However, sql.Open does not actually connect yet. So call db.Ping() to check that the database really answers. In fact, every Go database program starts with these few lines.

Creating a Table and Inserting Rows

_, err = db.Exec(`CREATE TABLE IF NOT EXISTS users (
	id   INTEGER PRIMARY KEY AUTOINCREMENT,
	name TEXT NOT NULL,
	age  INTEGER NOT NULL
)`)

res, err := db.Exec("INSERT INTO users (name, age) VALUES (?, ?)", "Asha", 28)
if err != nil {
	log.Fatal(err)
}
id, _ := res.LastInsertId()
fmt.Println("new user id:", id) // new user id: 1

In a Go database program, use Exec for statements that change data. The ? marks are placeholders, and the driver fills them in safely. As a result, user input can never break your SQL, which blocks SQL injection attacks.

Reading Data from a Go Database

QueryRow: One Row

var name string
var age int
err = db.QueryRow("SELECT name, age FROM users WHERE id = ?", 1).Scan(&name, &age)
if err != nil {
	log.Fatal(err)
}
fmt.Println(name, age) // Asha 28

Scan copies each column into a variable, in order. So you pass pointers, written with &, as you learned in pointers in Go.

Query: Many Rows

rows, err := db.Query("SELECT id, name, age FROM users WHERE age >= ?", 18)
if err != nil {
	log.Fatal(err)
}
defer rows.Close()

var users []User
for rows.Next() {
	var u User
	if err := rows.Scan(&u.ID, &u.Name, &u.Age); err != nil {
		log.Fatal(err)
	}
	users = append(users, u)
}
if err := rows.Err(); err != nil {
	log.Fatal(err)
}
fmt.Println(users) // [{1 Asha 28} {2 Ravi 34}]

The diagram below shows this loop. First, Query sends the SQL. Then Next moves to each row, and Scan fills your struct. Finally, Close returns the connection to the pool.

Go Database diagram showing the query flow from your code through database/sql and the driver, then rows.Next and Scan

Query returns rows, Next and Scan read them one at a time, and Close hands the connection back to the pool.

Handling “No Rows” Correctly

err = db.QueryRow("SELECT name, age FROM users WHERE id = ?", 99).Scan(&name, &age)
if errors.Is(err, sql.ErrNoRows) {
	fmt.Println("no user with id 99")
}

An empty result is not a crash, so treat it as a normal case. In a web API, for instance, sql.ErrNoRows usually becomes a 404 response.

Updating Rows and Using Transactions

res, err = db.Exec("UPDATE users SET age = ? WHERE id = ?", 29, 1)
n, _ := res.RowsAffected()
fmt.Println("updated rows:", n) // updated rows: 1

tx, err := db.Begin()
if err != nil {
	log.Fatal(err)
}
if _, err := tx.Exec("DELETE FROM users WHERE id = ?", 2); err != nil {
	tx.Rollback()
	log.Fatal(err)
}
if err := tx.Commit(); err != nil {
	log.Fatal(err)
}

A transaction groups several statements, so either all of them succeed or none do. For example, a bank transfer must take money from one account and add it to another together.

The Go Database Connection Pool

sql.DB is not one connection. Instead, it manages a pool of connections and reuses them. So create it once at startup and share it across your whole Go database layer. You can also tune the pool with db.SetMaxOpenConns(10) and db.SetMaxIdleConns(5).

Common Go Database Mistakes

Error you seeWhy it happensHow to fix it
sql: unknown driver “sqlite” (forgotten import?)The driver was never imported.Add the blank import for the driver.
sql: expected 2 destination arguments in Scan, not 1Scan got fewer variables than columns.Pass one pointer per column.
sql: Scan error on column index 0, name “name”Variables are in the wrong order or type.Match the SELECT order exactly.
Connections run outThe code forgot rows.Close().Always defer rows.Close().

Database questions are common in backend interviews too. So practise with my Go interview questions and answers.

Official Resources

These pages come straight from the Go team, so they stay accurate and up to date.

Quick Recap

  • Go database code uses database/sql plus a driver.
  • sql.Open prepares the pool, and Ping checks the connection.
  • Use Exec for changes and Query or QueryRow for reads.
  • Always use ? placeholders, close rows and check rows.Err().
  • Transactions make several statements succeed or fail together.

What’s Next?

You can now store data that survives a restart. Next, we will look closely at text by working with strings, runes and the strings package.

Next lesson: Go Strings Explained with Examples