08sqlx

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 08: sqlx, database/sql with the boilerplate removed.

github.com/jmoiron/sqlx wraps database/sql (sqlx.DB embeds *sql.DB, so everything from lesson 02 still works) and adds:

  • struct scanning via `db:"column"` tags: Get (one row), Select (many rows), StructScan
  • named parameters: NamedExec / NamedQuery with :field placeholders bound from a struct or map
  • sqlx.In: expands a slice into IN (?, ?, ?) because database/sql cannot bind a slice
  • Rebind: rewrites ? placeholders for the target driver ($1, $2 for PostgreSQL)

Compare with lesson 02: there we wrote Scan(&t.ID, &t.ProjectID, ...) and a for rows.Next() loop by hand, in the right column order, for every query. With sqlx, adding a column means adding a struct field.

Rules and gotchas:

  • Column names must map to struct fields; an unmapped column is an error ("missing destination name"). Select only what the struct has, or add `db:"-"` / extra fields.
  • Without tags sqlx lower-cases field names (AssigneeID -> assigneeid), so always tag.
  • Select loads ALL rows into memory. For huge results iterate with Queryx + StructScan.
  • sqlx is still runtime-checked: a typo in SQL or a tag is found when the query runs.
  • sqlx.In returns a query with ? marks; call db.Rebind(query) before running it so it works on PostgreSQL too. An EMPTY slice makes sqlx.In return an error, so guard it.

In industry: sqlx is a very common middle ground. You still write plain SQL (full control, easy to optimise) but skip repetitive scanning code. Teams that want compile-time checked queries move on to sqlc (lesson 09).

Jump to

Keyboard shortcuts

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