0
0
mirror of https://github.com/rbock/sqlpp11.git synced 2024-12-27 00:16:59 +08:00
sqlpp11/docs/Prepared-Statements.md
Farook Al-Sammarraie 993ddcc049
Created docs directory (#364)
Copied wiki into docs directory
This allows developers to open pull requests to edit documentation and also use mkdocs to create a styled HTML version

* changed wiki links to relative links

* removed Planned-Features.md

* removed reference to planned features in Home.md
2021-05-09 09:01:22 +02:00

1.6 KiB

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:

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:

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.

auto prepared_statement = db.prepare(some_statement);

You can now set the parameters and execute the prepared statement multiple times, e.g.

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...