Prepared Statements
Run parameterized queries.
Prepared Statements is a free Go Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is a Prepared Statement
A prepared statement sends the SQL text to the database once to be parsed and planned, then executes it many times with different parameters. It is faster for repeated queries and safer against injection.
Parameter Placeholders
Never build SQL by concatenating user input. Use placeholders so the driver sends values separately. PostgreSQL uses $1, $2; MySQL and SQLite use ?.
SELECT * FROM users WHERE age > $1 AND city = $2Why This Stops Injection
Because parameters travel apart from the SQL text, the database treats them strictly as data, never as code. A malicious value like " OR 1=1 becomes a literal string, not executable SQL.
db.Prepare
Prepare returns a *sql.Stmt tied to the pool. You then call Exec or Query on the statement with arguments.
stmt, err := db.Prepare("INSERT INTO users(name, age) VALUES($1, $2)")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()Executing the Statement
Call stmt.Exec with arguments for each placeholder. For inserts and updates, Exec returns a sql.Result with rows affected and last insert id.
res, err := stmt.Exec("Ada", 36)
if err != nil {
log.Fatal(err)
}
n, _ := res.RowsAffected()
fmt.Println("inserted", n)Reusing in a Loop
The win comes from reuse: prepare once, execute many times inside a loop. The database reuses its parsed plan for every call.
for _, u := range users {
if _, err := stmt.Exec(u.Name, u.Age); err != nil {
log.Fatal(err)
}
}Implicit Preparation
Passing args to db.Query or db.Exec directly also uses placeholders safely; the driver may prepare under the hood. Explicit Prepare matters mainly for repeated execution.
A Runnable Parameter-Binding Simulation
Real prepared statements need a database. This runnable example simulates safe parameter binding to show how values stay separate from the query text.
package main
import "fmt"
func execPrepared(query string, args ...interface{}) string {
return fmt.Sprintf("EXEC %q with args %v", query, args)
}
func main() {
q := "INSERT INTO users(name, age) VALUES($1, $2)"
people := [][2]interface{}{{"Ada", 36}, {"Lin", 41}}
for _, p := range people {
fmt.Println(execPrepared(q, p[0], p[1]))
}
}Context Variants
Use PrepareContext and stmt.ExecContext so prepared calls respect timeouts and cancellation, just like the rest of database/sql.
Always Close the Stmt
A *sql.Stmt holds resources on the database. Defer stmt.Close() when you are done. Leaking statements can exhaust server-side prepared statement limits.
Statements and Pooling
A statement prepared on *sql.DB works across pooled connections; the library re-prepares it on whichever connection it lands on. You usually do not manage this yourself.
Quick Check
Test your prepared statement knowledge.
Recap
You learned prepared statements:
- Prepare parses once, execute many times
- Placeholders ($1 or ?) keep values as data, stopping injection
- stmt.Exec returns rows affected; defer stmt.Close()
- Reuse in loops; use Context variants for deadlines
Frequently asked questions
Is the “Prepared Statements” lesson free?
Yes — the full text of “Prepared Statements” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Prepared Statements”?
Run parameterized queries. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Prepared Statements” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Opening a Connection
- Querying Rows
- Prepared Statements
- Transactions