0
0
mirror of https://github.com/rbock/sqlpp11.git synced 2024-12-25 23:40:50 +08:00
sqlpp11/docs/Prepared-Statements.md

49 lines
1.6 KiB
Markdown
Raw Permalink Normal View History

# Introduction
Executing a statement in a database is typically done in two phases: First, the statement is prepared (parsed, compiled, optimized). Then, it is run against the database. Since statements often differ only in parameters, not in structure, many databases offer to store prepared statements. These prepared statements can then be executed repeatedly, typically with some parameters.
sqlpp11 supports prepared statements.
## Parameters
Currently there are two overloads to specify a parameter:
```C++
parameter(const ValueType&, const AliasProvider&);
parameter(const NamedExpression&)
```
Value types are sqlpp::bigint, sqlpp::text, etc., Alias providers can be generated by using the SQLPP_ALIAS_PROVIDER macro, and named expressions are combinations of the former, e.g. columns of a table.
For instance, you could use:
```C++
SQLPP_ALIAS_PROVIDER(cheese);
parameter(sqlpp::bigint(), cheese);
parameter(tab.id);
```
## Prepare and execute statements
insert, update, remove and select statements can be prepared by calling the `prepare()` method of a database connection object.
```C++
auto prepared_statement = db.prepare(some_statement);
```
You can now set the parameters and execute the prepared statement multiple times, e.g.
```C++
auto prepared_insert = db.prepare(
insert_into(tab).set(
tab.alpha = parameter(tab.alpha),
tab.beta = parameter(sqlpp::text(), cheese)
));
for (const auto& input : input_values)
{
prepared_insert.params.alpha = input.first;
prepared_insert.params.cheese = input.second;
db(prepared_insert);
}
```
Note: need nicer examples...