02database-sql

command
v0.0.0-...-610d9af Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: GPL-3.0 Imports: 7 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL