sqlx
sqlx is a third-party layer on database/sql that scans rows into structs, supports named parameters, and keeps the same pool and context model. It is not an ORM.
Detailed Explanation
rows.Scan(&id, &name, &email) gets old when a table has twenty columns. sqlx.GetContext(ctx, db, &user, query, args...) fills User by column name and db tag. SelectContext fills a slice. You still write SQL. You still use a driver. You still have a *sql.DB (or *sqlx.DB, which embeds it).
Named parameters. sqlx can rewrite WHERE id = :id to $1 or ? for the driver. Pass a struct or map[string]any of arguments. This is convenience, not a different security model: values are still bound.
StructScan and tags. `db:"user_id"` maps a column to a field. Exported fields only, same as JSON. Embedded structs work with a bit of care. Get expects one row and fills fields whose db tags match selected columns. Extra struct fields stay zero. Extra selected columns that have no field are an error unless you use a more permissive helper.
When not to. A two-column query is clearer with Scan. A full graph of relations is an ORM job (GORM, ent, sqlc). sqlc generates typed code from SQL and is a common alternative to sqlx when you want compile-time column checks.
What it costs. A module (github.com/jmoiron/sqlx). Reflection on each scan. The usual database/sql rules still apply: close rows, use context, one pool. sqlx will not save you from N+1 queries; you still write the SQL.
Code Examples
package main
import (
"context"
"github.com/jmoiron/sqlx"
_ "github.com/jackc/pgx/v5/stdlib"
)
type User struct {
ID int64 `db:"id"`
Email string `db:"email"`
}
func find(ctx context.Context, db *sqlx.DB, id int64) (User, error) {
var u User
err := db.GetContext(ctx, &u, `SELECT id, email FROM users WHERE id = $1`, id)
return u, err
}
func main() {}func list(ctx context.Context, db *sqlx.DB) ([]User, error) {
var out []User
err := db.SelectContext(ctx, &out, `SELECT id, email FROM users`)
return out, err
}Common Gotchas
`Get` returns `sql.ErrNoRows` on miss
handle it like `QueryRow`.
Column names must match `db` tags (or lowercase field names)
`UserID` will not bind `user_id` without a tag.
`sqlx.DB` embeds `sql.DB`
pooling knobs are the same methods.