Go's standard library handles relational databases through the database/sql package, a driver-agnostic interface for connection pooling, queries, prepared statements and transactions. You import a driver for your database (PostgreSQL, MySQL, SQLite and others), open a *sql.DB, and use its context-aware methods such as QueryContext, QueryRowContext and ExecContext.
The standard library has no ORM and no driver of its own. That is deliberate: database/sql keeps your code portable, and you add helpers such as sqlc or sqlx only when you need them.
ExecContextsql.Open does not connect. It validates its arguments and returns a *sql.DB, which is a pool that is safe for concurrent use. Create it once at startup, share it across goroutines, and call PingContext to confirm the database is reachable. This example uses PostgreSQL through the pgx driver's database/sql adapter.
The blank import (_) runs the driver's init function so it registers itself under a name. For MySQL use github.com/go-sql-driver/mysql with the name mysql. The pool settings stop your service from opening unlimited connections and recycle old ones before a load balancer or firewall drops them.
Always pass user input as query parameters, never by concatenating strings, so the database treats it as data. Placeholder syntax depends on the driver: $1, $2 for PostgreSQL and ? for MySQL and SQLite.
Three habits prevent most bugs: defer rows.Close() returns the connection to the pool, rows.Err() reports errors that ended iteration early, and the Scan destinations must match the selected columns in order and type.
QueryRowContext returns at most one row. When nothing matches, Scan returns sql.ErrNoRows, which you should compare with errors.Is. Nullable columns need sql.NullString, sql.NullInt64 and similar types, or pointer fields.
Translating sql.ErrNoRows into your own error keeps database/sql details out of your HTTP handlers.
ExecContextExecContext runs statements that do not return rows. It gives you a sql.Result with RowsAffected, which is how you detect an update that matched nothing. LastInsertId is not supported by every driver (PostgreSQL does not support it), so use RETURNING there.
A transaction groups several statements so they all succeed or all roll back. Begin with BeginTx, defer a Rollback (which is a harmless no-op after a successful Commit), and commit at the end.
Use the tx object for every statement inside the transaction. Calling db instead would run on a different connection, outside the transaction. If the context is cancelled, the transaction rolls back automatically.
db.PrepareContext creates a statement you can run many times, which helps when you execute the same query in a loop. For one-off queries, the driver already uses parameterised queries, so preparing is optional.
| Technique | When to use it |
|---|---|
SetMaxOpenConns | Always, to stay under the database's connection limit |
PrepareContext | Repeated identical statements in a loop |
| Transactions | Multi-statement changes that must be atomic |
Batch inserts or COPY | Loading thousands of rows (driver-specific, for example pgx.CopyFrom) |
sqlc or sqlx | Generating typed query code or reducing Scan boilerplate |
context timeouts | Preventing slow queries from holding connections forever |
sql.Open connect to the database?No. It only prepares the pool. The first connection is made lazily, so call db.PingContext to verify the database is reachable.
*sql.DB after every query?No. Create one *sql.DB per database, share it, and close it when the program exits. Close Rows and Stmt objects instead.
Use placeholders and pass values as arguments to QueryContext or ExecContext. Never build SQL by joining strings with user input.
database/sql enough, or do I need an ORM?It is enough for many services. Add sqlc, sqlx or an ORM such as GORM only if you want generated code or less boilerplate.
Open one *sql.DB pool at startup and configure its limits, use the context-aware query methods with placeholders, close rows and check rows.Err(), handle sql.ErrNoRows with errors.Is, and wrap multi-step changes in transactions. These habits give you safe, portable and performant database code with nothing beyond the standard library and a driver.