database/sql
database/sql is the standard library's generic SQL API. You open a *sql.DB with a driver name and DSN, then QueryContext, ExecContext, and PrepareContext. The package pools connections; it is not a dialect.
Detailed Explanation
sql.Open("pgx", dsn) does not necessarily dial. It stores the driver and DSN. The pool opens connections as queries need them. PingContext is how you fail fast at startup. Close on the *sql.DB closes the pool, not one connection — you keep one *sql.DB for the process.
DB, Conn, Tx, Stmt, Rows. DB is the pool. Conn is one connection from the pool (rarely needed). Tx is a transaction. Stmt is a prepared statement. Rows is a cursor; you Scan each row and Close the rows (or defer rows.Close()). QueryRowContext is a single row; Err() after Scan includes sql.ErrNoRows.
Always take context.Context. The Query methods without context exist for history. The *Context methods cancel the query when the request ends.
Scanning. Scan maps columns to pointers. Types must match what the driver provides (int64 for BIGINT, []byte or string for text, sql.NullString for nullable text). A schema change that adds a column you do not scan is fine; one you scan with the wrong type is an error.
What it costs. database/sql is the portable layer. Drivers do the real protocol. An ORM on top still uses this package or replaces it. The mistakes that hurt are: one DB per request, leaking Rows, ignoring ErrNoRows, and queries without context.
Code Examples
package main
import (
"context"
"database/sql"
"fmt"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
func open(dsn string) (*sql.DB, error) {
db, err := sql.Open("pgx", dsn)
if err != nil {
return nil, err
}
db.SetMaxOpenConns(10)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
return db, db.PingContext(ctx)
}
func name(ctx context.Context, db *sql.DB, id int64) (string, error) {
var n string
err := db.QueryRowContext(ctx, `SELECT name FROM users WHERE id = $1`, id).Scan(&n)
if err == sql.ErrNoRows {
return "", fmt.Errorf("user %d: %w", id, err)
}
return n, err
}
func main() {}Common Gotchas
`sql.Open` success is not a live connection
`PingContext` at startup.
`QueryRow` without checking `ErrNoRows` looks like a broken scan
`QueryRow` without checking `ErrNoRows` looks like a broken scan