The following sample, excerpted from the article, demonstrated the simplicity of the library.
- Session and Statement classes hide OCI calls from the users.
- Free function use() binds variables to placeholders in the SQL statements.
- Free function into() populates the variables with the values returned by select statements.
- Shift operator in the Session enables storing a query and starts creating a temporary object that handles the rest of the expression.
- Comma operator stores parameter information returned by use and into functions into the temporary object for later use.
- The temporary object executes the sql statements in its destructor.
#include "soci.h"
#include <iostream>
using namespace std;
using namespace SOCI;
int main()
{
try
{
Session sql("DBNAME", "user", "password");
// example 1. - basic query with one variable used
int count;
sql << "select count(*) from some_table", into(count);
// example 2. - basic query with parameter
int id = 7;
string name;
sql << "select name from person where id = " << id, into(name);
// example 3. - the same, but with input variable
sql << "select name from person where id = :id", into(name), use(id);
// example 4. - statement with no output
id = 8;
name = "John";
sql << "insert into person(id, name) values(:id, :name)", use(id), use(name);
// example 5. - statement used multiple (three) times
Statement st1 = (sql.prepare <<
"insert into country(id, name) values(:id, :name)",
use(id), use(name));
id = 1; name = "France"; st1.execute(1);
id = 2; name = "Germany"; st1.execute(1);
id = 3; name = "Poland"; st1.execute(1);
// example 6. - statement used for fetching many rows
Statement st2 = (sql.prepare << "select name from country", into(name));
st2.execute();
while (st2.fetch())
{
cout << name << '\n';
}
}
catch (exception const &e)
{
cerr << "Error: " << e.what() << '\n';
}
}
No comments:
Post a Comment