How to Use Prepared Statements in Go

Use db.Prepare() to create a reusable SQL statement with placeholders, then execute it with stmt.Query() or stmt.Exec() for safe, efficient database operations.

Use the database/sql package to prepare a statement with db.Prepare(), then execute it repeatedly with stmt.Query() or stmt.Exec(), passing parameters as arguments.

stmt, err := db.Prepare("SELECT name, email FROM users WHERE age > ?")
if err != nil {
    log.Fatal(err)
}
defer stmt.Close()

rows, err := stmt.Query(21)
if err != nil {
    log.Fatal(err)
}

The ? placeholder is replaced by the value 21 at execution time, preventing SQL injection and improving performance for repeated queries.