Sobes.tech
Middle

What are prepared statements?

sobes.tech AI

Answer from AI

Prepared statements are a mechanism in database operations where an 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 injection, as parameters are passed separately from the query text.
  • Convenience — parameters are automatically substituted, eliminating the need to manually escape values.

In Go, a prepared statement 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)

Thus, the query is compiled once, and then it can be called multiple times with different parameters.

What are prepared statements? — Golang - sobes.tech