API Reference

sqlx

Extensions for database/sql in Go that scan rows into structs with tagged fields and named queries.

Official Documentation ↗
CompatibilityThis documentation covers version v1.4. Check the official docs for the latest API surface.

Installation

gogo get github.com/jmoiron/sqlx

Methods

Extensions for database/sql in Go that scan rows into structs with tagged fields and named queries.

Overview

sqlx keeps hand-written SQL but removes the manual Scan plumbing. Structs with db tags receive rows directly through Get and Select, named queries bind by field name, and Rebind smooths placeholder differences between drivers.

It stays a thin layer over database/sql: connections, transactions, and driver behavior are unchanged, which makes adoption low-risk for teams that want ergonomics without an ORM.

Core Methods

The most frequently used entry points, with signatures and runnable examples:

  • sqlx.Connect / MustConnect — Opens and pings the database, returning a handle that also carries sqlx extensions.
  • Get / Select — Scans one row, or a full result set, into a struct or slice using db struct tags.
  • NamedExec — Runs statements whose placeholders bind from struct fields or map keys via :name syntax.
  • Unsafe / Rebind — Unsafe ignores missing destination fields; Rebind converts placeholders to the driver dialect.

Usage Notes

  • List columns explicitly instead of SELECT * so tag drift fails loudly at compile-test time.
  • Wrap writes in transactions with Beginx and named Tx methods for consistent semantics.
  • Prefer errors.Is(err, sql.ErrNoRows) checks to separate absence from breakage.

Common Pitfalls

  • SELECT * combined with partial structs errors unless Unsafe, which then silently drops columns.
  • Forgetting defer rows.Close() with Queryx leaks connections until GC.
  • Column alias mismatches, AS total versus tag total_price, surface at runtime only.

Errors

The following points are quoted verbatim from the official documentation. 来源:https://jmoiron.github.io/sqlx/ · 取证方式:HTTP GET 官方 README/文档页(HTML 去标签) · 抓取时间:2026-11-07T13:52:38.925Z. Any error type, throw condition or recovery step not stated there is left unspecified; this page does not infer exception classes or return values.

FAQ

How does sqlx relate to database/sql?
sqlx embeds *sql.DB and adds convenience: Get, Select, struct scanning, named parameters. Everything from database/sql, transactions, prepared statements, rows, still works, so drivers and pooling behave identically.
Why does Get return sql.ErrNoRows?
Get maps to QueryRow semantics: an empty result surfaces as sql.ErrNoRows rather than nil. Distinguish missing rows with errors.Is(err, sql.ErrNoRows) before treating it as a failure.
What do struct tags need to match?
Fields tagged db:"column" must match result column names exactly, case-sensitively for most drivers. Untagged exported fields fall back to their lowercase name; mismatches error unless the handle is Unsafe.