SQL Injection Prevention Implementation in Go
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓SQL Injection Prevention runs in O(n) time and O(n) space, in Go as in every other language.
- ✓database/sql is the standard boundary: db.QueryContext(ctx, "... where id = $1", id) hands the arguments to the driver and never to a formatter, and sql.Named covers drivers with named parameters.
- ✓fmt.Sprintf holding a query string is an instant reject, and gosec flags it as G201/G202. Values go after the query string, always, including ints.
- ✓The Go trap: Go's two footguns live in the DSN, far from any query. go-sql-driver/mysql accepts multiStatements=true, off by default: turn it on for a migration tool and every injection anywhere in that process is upgraded from one statement to a stacked one.
- ✓database/sql with arguments, on a driver without a fast path, does prepare, execute and close for each call, up to three round trips per query.
What SQL Injection Prevention actually is
SQL Injection Prevention in Go: what you actually reach for
Go implementation
package store
import (
"context"
"database/sql"
"fmt"
)
// The planner needs the ORDER BY column at parse time, so it cannot be a
// placeholder. Map the request token onto a constant instead.
var sortable = map[string]string{
"created": "created_at",
"name": "display_name",
}
func Search(ctx context.Context, db *sql.DB, term, sort string, limit int) ([]string, error) {
column, ok := sortable[sort]
if !ok {
return nil, fmt.Errorf("unsortable column %q", sort)
}
// Only the allowlisted constant is formatted in; term and limit are bound.
q := fmt.Sprintf(
`SELECT display_name FROM customer WHERE display_name ILIKE $1 ORDER BY %s DESC LIMIT $2`,
column)
rows, err := db.QueryContext(ctx, q, "%"+term+"%", limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []string
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
return nil, err
}
out = append(out, name)
}
return out, rows.Err()
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Go-specific trap
Performance in Go, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for SQL Injection Prevention?
database/sql is the standard boundary: db.QueryContext(ctx, "... where id = $1", id) hands the arguments to the driver and never to a formatter, and sql.Named covers drivers with named parameters. The placeholder dialect belongs to the driver, not the language: $1 for jackc/pgx and lib/pq, ? for go-sql-driver/mysql and mattn/go-sqlite3, @p1 for microsoft/go-mssqldb, which is why copying a query between projects is where the bug usually enters. pgx v5 is the Postgres standard and adds pgx.Identifier{"public", "customer"}.Sanitize() for the identifier case that placeholders cannot serve.
What is the most common Go mistake when implementing SQL Injection Prevention?
Go's two footguns live in the DSN, far from any query. go-sql-driver/mysql accepts multiStatements=true, off by default: turn it on for a migration tool and every injection anywhere in that process is upgraded from one statement to a stacked one. The same driver takes interpolateParams=true, which stops using server-side prepares and builds the SQL client-side instead. The escaping stays correct, but you have swapped the parse-before-data guarantee for a saved round trip, so a placeholder-shaped code path becomes indistinguishable from a hand-built string on the wire. Neither setting shows up when reviewing the query itself.
How does SQL Injection Prevention actually perform in Go?
database/sql with arguments, on a driver without a fast path, does prepare, execute and close for each call, up to three round trips per query. A *sql.Stmt is cached per pooled connection, so reusing one across the pool re-prepares on each new backend rather than sharing anything. pgx used natively rather than through database/sql keeps a per-connection statement cache and speaks the binary protocol, which is why hot paths drop the abstraction. The mysql driver's interpolateParams=true collapses two round trips into one at the cost described above. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.