Middle
Mis on ettevalmistatud päringud (prepared statements)?
sobes.tech AI
Vastus AI-lt
Prepared statements are a mechanism for working with databases, where the SQL query is compiled and optimized once, and then can be executed multiple times with different parameters.
Advantages:
- Increased performance when calling the same query repeatedly.
- Security — protection against SQL injections, as parameters are passed separately from the query text.
- Convenience — parameters are automatically inserted, no need to manually escape values.
In Go, a prepared query is created using the Prepare method of the *sql.DB or *sql.Tx object:
stmt, err := db.Prepare("SELECT name FROM users WHERE id = ?")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
var name string
err = stmt.QueryRow(1).Scan(&name)
if err != nil {
log.Fatal(err)
}
fmt.Println(name)
This way, the query is compiled once, and can be called multiple times with different parameters.