Documentation
¶
Overview ¶
Lesson 02: database/sql, Go's standard database API.
database/sql is a thin, driver-agnostic layer. You import a driver for its side effect (`_ "modernc.org/sqlite"` registers the name "sqlite"), then talk only to *sql.DB.
Key facts:
- sql.Open does NOT connect. It validates arguments and returns a lazy handle. Call db.PingContext to prove the database is reachable (do it once at startup).
- *sql.DB is NOT a connection. It is a concurrency-safe POOL. Create one per database, share it everywhere, and close it only at program shutdown.
- ExecContext -> statements with no rows back (INSERT/UPDATE/DELETE), returns sql.Result.
- QueryContext -> many rows; you MUST rows.Close() (defer it) and check rows.Err() after the loop.
- QueryRowContext -> exactly one row; errors surface at .Scan(); no row = sql.ErrNoRows.
- Always pass a context so queries are cancelled on timeout / client disconnect.
- NULL handling: scanning NULL into a plain string/int fails. Use sql.Null[T] (generic, Go 1.22+), sql.NullString, or a pointer (*string). Pick one style and stay consistent.
- RETURNING id (SQLite 3.35+, PostgreSQL) is the portable way to get a new id. res.LastInsertId() works in SQLite/MySQL but NOT in PostgreSQL drivers.
Connection pool settings (defaults: unlimited open, 2 idle, no lifetime limit):
- SetMaxOpenConns cap on total connections. Protects the database from your app. SQLite allows one writer at a time, so small numbers are fine here.
- SetMaxIdleConns connections kept warm for reuse. Too low = constant reconnecting.
- SetConnMaxLifetime / SetConnMaxIdleTime recycle connections so load balancers, failovers and server-side timeouts do not leave you holding dead ones.
Gotchas:
- Forgetting rows.Close() leaks a connection; the pool eventually runs dry and hangs.
- Ignoring rows.Err() hides errors that happen mid-iteration (network drop, cancelled ctx).
- Do not use Query for INSERT/UPDATE; use Exec.
In industry: services open one *sql.DB at startup, ping it, set pool limits from config (often MaxOpen around 10-25 per instance, because instances x MaxOpen must stay below the database's connection limit), and hide queries behind a repository / store type.