Using Prepared Statements - The Go Programming Language
Using Prepared Statements - The Go Programming Language
You can define a prepared statement for repeated use. This can help your code run a bit faster by
avoiding the overhead of re-creating the statement each time your code performs the database
operation.
Note: Parameter placeholders in prepared statements vary depending on the DBMS and driver
you’re using. For example, the pq driver for Postgres requires a placeholder like $1 instead of ?.
A prepared statement is SQL that is parsed and saved by the DBMS, typically containing
placeholders but with no actual parameter values. Later, the statement can be executed with a set
of parameter values.
When you expect to execute the same SQL repeatedly, you can use an sql.Stmt to prepare the
SQL statement in advance, then execute it as needed.
The following example creates a prepared statement that selects a specific album from the
database. DB.Prepare returns an sql.Stmt representing a prepared statement for a given SQL
text. You can pass the parameters for the SQL statement to Stmt.Exec, Stmt.QueryRow, or
Stmt.Query to run the statement.
A prepared sql.Stmt provides the usual Exec, QueryRow, and Query methods for invoking the
statement. For more on using these methods, see Querying for data and Executing SQL
statements that don’t return data.
However, because an sql.Stmt already represents a preset SQL statement, its Exec, QueryRow,
and Query methods take only the SQL parameter values corresponding to placeholders, omitting
the SQL text.
You can define a new sql.Stmt in different ways, depending on how you will use it.
Be sure that stmt.Close is called when your code is finished with a statement. This will release
any database resources (such as underlying connections) that may be associated with it. For
statements that are only local variables in a function, it’s enough to defer stmt.Close().
Function Description
Tx.Prepare Prepare a statement for use in a specific transaction. For more, see Executing
Tx.PrepareContext transactions.
Tx.Stmt
Tx.StmtContext
Conn.PrepareContext For use with reserved connections. For more, see Managing connections.
https://go.dev/doc/database/prepared-statements 2/3
8/27/24, 9:08 PM Using prepared statements - The Go Programming Language
Function Description
https://go.dev/doc/database/prepared-statements 3/3