SQLite from Go: connections, drivers and types · 5 MIN READ

Open a SQLite database from Go: database/sql, a driver and a file

Open a file database through database/sql, see that sql.Open connects lazily, and run Exec, Query and QueryRow with placeholders and complete error handling.

SQLite is a library, not a server: your Go process opens a single file and runs the SQL engine in its own address space. database/sql supplies the pool, statements and transactions; a driver supplies the engine. This course uses the pure-Go modernc.org/sqlite driver for its runnable examples, and every program here works the same in a native Go environment. The next GopherForge update adds a SQLite project template whose Go program uses database/sql through the app's bundled gopherforge.app/sqlite driver (registered as sqlite, backed by the system SQLite on iPhone and iPad); databases a program writes under /sandbox are kept with the project; and a database browser per project shows tables, schema and rows, offers a SQL console, and imports and exports .sqlite and .db files through Files.

sqlite · A MAP OF THE IDEA

  1. sql.Open once
  2. PingContext at startup
  3. Exec and Query with ?
  4. Close rows, check Err

Useful when

  • One process, one file: no server to install or operate.
  • database/sql code stays the same across SQLite drivers.

Watch out

  • Configuration errors surface on first use unless you Ping.
  • Every pooled connection has its own settings and state.

Implementation & operation cost: A single shared *sql.DB, a Ping at startup and the discipline of closing every Rows value.

01

A database handle is a pool, not a connection

sql.Open checks the driver name and remembers the data source name. It does not touch the disk, so a misspelt path or a read-only directory is reported by the first statement, not by Open. The *sql.DB it returns is a concurrency-safe pool that opens connections on demand and keeps idle ones for reuse; create it once at startup, share it, and Close it at shutdown. Call PingContext right after Open when you want configuration errors at startup instead of on the first request. With SQLite each pooled connection is a separate open of the same file with its own page cache, its own PRAGMA settings and its own transaction state, which is why later lessons care so much about how many connections exist.

02

Create, insert and read back

The program opens app.db in a temporary directory, shows that the file appears only once Ping opens a real connection, creates a table and inserts three rows with ? placeholders. Arguments always travel separately from the SQL text, so a title containing a quote cannot change the statement. LastInsertId returns the new rowid for each insert, RowsAffected reports how many rows an UPDATE touched, and a QueryRow that finds nothing reports sql.ErrNoRows from Scan.

go
package main

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"log"
	"os"
	"path/filepath"

	_ "modernc.org/sqlite" // registers the driver name "sqlite"
)

func exists(path string) bool {
	_, err := os.Stat(path)
	return err == nil
}

func main() {
	ctx := context.Background()
	dir, err := os.MkdirTemp("", "first-db")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "app.db")

	db, err := sql.Open("sqlite", path)
	if err != nil {
		log.Fatal(err) // only a bad driver name or DSN fails here
	}
	defer db.Close()
	fmt.Println("after sql.Open, file exists:", exists(path))

	if err := db.PingContext(ctx); err != nil {
		log.Fatal(err)
	}
	fmt.Println("after Ping, file exists:", exists(path))

	var version string
	if err := db.QueryRowContext(ctx, "SELECT sqlite_version()").Scan(&version); err != nil {
		log.Fatal(err)
	}
	fmt.Println("SQLite library major version:", version[:1])

	if _, err := db.ExecContext(ctx, `CREATE TABLE books (
		id    INTEGER PRIMARY KEY,
		title TEXT NOT NULL,
		year  INTEGER NOT NULL
	)`); err != nil {
		log.Fatal(err)
	}

	books := []struct {
		title string
		year  int
	}{{"The Go Programming Language", 2015}, {"Concurrency in Go", 2017}, {"Learning Go", 2021}}
	for _, b := range books {
		res, err := db.ExecContext(ctx, "INSERT INTO books (title, year) VALUES (?, ?)", b.title, b.year)
		if err != nil {
			log.Fatal(err)
		}
		id, _ := res.LastInsertId()
		fmt.Printf("inserted id=%d %q\n", id, b.title)
	}

	rows, err := db.QueryContext(ctx, "SELECT id, title FROM books WHERE year >= ? ORDER BY year", 2016)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	for rows.Next() {
		var id int64
		var title string
		if err := rows.Scan(&id, &title); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("since 2016: %d %s\n", id, title)
	}
	if err := rows.Err(); err != nil { // an error that ended the loop early
		log.Fatal(err)
	}

	var title string
	err = db.QueryRowContext(ctx, "SELECT title FROM books WHERE year = ?", 1999).Scan(&title)
	fmt.Println("no book from 1999:", errors.Is(err, sql.ErrNoRows))

	res, err := db.ExecContext(ctx, "UPDATE books SET year = year + 1 WHERE year < ?", 2020)
	if err != nil {
		log.Fatal(err)
	}
	n, _ := res.RowsAffected()
	fmt.Println("rows updated:", n)
}
Read the code

The first two lines show the lazy open: false after sql.Open, true after Ping. The library version line prints only the major version, which is 3 for every SQLite in use today. The inserts receive ids 1, 2 and 3 because id is an INTEGER PRIMARY KEY. The query returns the two books from 2017 and 2021 in year order, the 1999 lookup reports sql.ErrNoRows, and the UPDATE touches the two books published before 2020.

03

Rows hold a connection until you are done

QueryContext borrows a connection from the pool and keeps it until the rows are closed. Always defer rows.Close() right after checking the error, read with rows.Next and rows.Scan, and check rows.Err() after the loop, because Next returns false both at the end and on a read error. A forgotten Close leaks a connection; with SQLite it can also keep a read transaction open, which stops a WAL checkpoint from resetting the log. QueryRowContext closes its rows for you inside Scan and turns an empty result into sql.ErrNoRows, which you test with errors.Is rather than by comparing message strings.

go
rows, err := db.QueryContext(ctx, query, args...)
if err != nil {
	return err
}
defer rows.Close()
for rows.Next() {
	if err := rows.Scan(&dest...); err != nil {
		return err
	}
}
return rows.Err()
Read the code

This is the shape of every multi-row read. The deferred Close runs even when Scan fails halfway, and the final rows.Err() distinguishes a complete result from one that a cancelled context or an I/O error cut short.

04

Placeholders and the statement cache

SQLite accepts ? for positional parameters and also ?NNN, :name, @name and $name. database/sql passes sql.Named arguments to drivers that support names, which modernc.org/sqlite does. Placeholders stand only for values: table names, column names, ORDER BY directions and PRAGMA arguments cannot be bound and must come from a fixed allow-list in your code. Each Exec or Query with arguments prepares a statement on the borrowed connection; when the same statement runs very often, db.PrepareContext keeps it prepared per connection, but measure before adding that complexity.

05

Where this runs

Every program in this course is a complete package main that runs natively with go run against modernc.org/sqlite, which is pure Go and needs no C compiler. The coming GopherForge update brings a SQLite project template to iPhone and iPad: its program uses the same database/sql calls through the bundled gopherforge.app/sqlite driver, registered under the driver name sqlite and backed by the system SQLite. Database files a program writes under /sandbox stay with the project, a per-project database browser (Project, then Databases) shows tables, schema, rows and a SQL console, and .sqlite and .db files can be imported and exported through Files. Until that update ships, run the examples in your own Go environment.

TAKE THIS WITH YOU

sql.Open only validates its arguments; Ping or the first statement opens a real SQLite connection. Share one *sql.DB, bind every value with placeholders, close rows, check rows.Err and treat sql.ErrNoRows as an expected outcome.

Check your understanding

You call sql.Open("sqlite", path) with a path inside a directory that does not exist. Where does the error appear?

Go to the source

Progress stays in this browser. No account needed.