Prepared statements
A prepared statement is SQL with placeholders ($1, ?) that you send separately from the argument values. QueryContext(ctx, q, args...) prepares or binds those arguments. Concatenating user text into the query string is how you get SQL injection.
Detailed Explanation
db.QueryContext(ctx, SELECT name FROM users WHERE id = $1, id) sends the query and the id as bound parameters. The database treats id as data, even if it contains quotes. That is the only safe way to mix SQL with user input.
Placeholders differ by driver. Postgres (pgx) uses $1, $2. MySQL and SQLite use ?. A query written for one will fail on the other. sqlx can use named :id and rewrite.
PrepareContext. stmt, err := db.PrepareContext(ctx, q) creates a statement you QueryContext many times. On a pool, a prepared statement is per connection; database/sql represents it as *sql.Stmt and re-prepares on other connections as needed. For a query you run once, QueryContext with args is enough — many drivers still use the extended protocol.
Reuse vs one-shot. Preparing helps when the SQL text is large and you run it thousands of times on the same connection. For typical request traffic, parameterized QueryContext is the readability win; measure before you cache *sql.Stmt on a struct.
What it costs. Bound parameters are the security baseline, not an optimization you skip. String-built WHERE clauses with unchecked identifiers (column names) are still injection if the identifier came from the user — parameters cannot substitute a column name. Allow-list those.
Code Examples
package main
import (
"context"
"database/sql"
)
func nameByID(ctx context.Context, db *sql.DB, id int64) (string, error) {
var name string
err := db.QueryRowContext(ctx,
`SELECT name FROM users WHERE id = $1`, id,
).Scan(&name)
return name, err
}
func main() {}func unsafe(id string) string {
return `SELECT name FROM users WHERE id = '` + id + `'` // injection
}Common Gotchas
Building SQL with `+` or `fmt.Sprintf` for values is injection
use `$1` / `?`.
`$1` vs `?` is driver-specific
a copied query will fail at run time, not compile time.
Identifiers (table, column) cannot be bound as parameters
allow-list them.