Prepared statements are SQL queries that you define once and then invoke as many times as you like, typically with varying parameters. More...
Prepared statements are SQL queries that you define once and then invoke as many times as you like, typically with varying parameters.
It's basically a function that you can define ad hoc.
If you have an SQL statement that you're going to execute many times in quick succession, it may be more efficient to prepare it once and reuse it. This saves the database backend the effort of parsing complex SQL and figuring out an efficient execution plan. Another nice side effect is that you don't need to worry about escaping parameters.
You create a prepared statement by preparing it on the connection, passing an identifier and its SQL text. The identifier is the name by which the prepared statement will be known; it should consist of letters, digits, and underscores only and start with a letter. The name is case-sensitive.
Once you've done this, you'll be able to call my_statement
from any transaction you execute on the same connection. Note that this uses a member function called "prepared"
; the definition used a member function called "prepare"
.
Did I mention that you can pass parameters to prepared statements? You define those along with the statement. The query text uses $1
, $2
etc. as placeholders for the parameters in the SQL text. Since your C++ compiler doesn't know how many parameters you're going to define, the syntax that lets you do this is a bit strange:
It's the ()() that declares the two parameters. If any of the parameters will be in binary form, you will pass treat_binary in the corresponding pair of parentheses.
When invoking the prepared statement, you pass parameter values using a similar syntax.