Starting with DbiXX
DbiXX is not mandatory part of CppCMS framework, it is just a general purpose library for executing SQL queries in safe way.
Let’s see a simple example:
#include <dbixx/dbixx.h>
#include <iostream>
using namespace dbixx;
using namespace std;
int main()
{
try {
session sql("sqlite3");
sql.param("dbname","test.db");
sql.param("sqlite3_dbdir","./");
sql.connect();
sql<<"DROP TABLE IF EXISTS users";
sql.exec();
sql<<"CREATE TABLE users ( "
" id integer primary key not null, "
" name varchar(128) not null "
");";
sql.exec();
sql<<"INSERT INTO users(id,name) VALUES(?,?)",
1,"Moshe",exec();
sql<<"INSERT INTO users(id,name) VALUES(?,?)",
2,"Yossi",exec();
sql<<"SELECT name FROM users WHERE id=?",1;
row r;
if(sql.single(r)) {
string name;
r>>name;
cout<<name<<endl;
}
else {
cout<<"No user with id="<<1<<endl;
}
result res;
sql<<"SELECT id,name FROM users";
sql.fetch(res);
cout<<"There are "<<res.rows()<<" users\n";
while(res.next(r)) {
int id;
string name;
r>>id>>name;
cout<<id<<"\t"<<name<<endl;
}
}
catch(std::exception const &e) {
cerr<<e.what()<<endl;
return 1;
}
return 0;
}
First we create a sql session object and load driver "sqlite3", then we setup all mandatory parameters needed by sqlite3 driver and create connection.
session sql("sqlite3");
sql.param("dbname","test.db");
sql.param("sqlite3_dbdir","./");
sql.connect();
Then we perform queries. First we prepare them using "iostreams like" style:
sql<<"DROP TABLE IF EXISTS users";
and then execute an operation:
sql.exec();
There is a syntactic sugar for this operation:
sql<<"DROP TABLE IF EXISTS users",exec();
Then we want to execute some command using parameters binding:
sql<<"INSERT INTO users(id,name) VALUES(?,?)",
1,"Moshe",exec();
First we load our query. Each "?" represents binded parameter. Then, using overloaded comma operator we bind actual values: integer "1" and string "Moshe". Note: every binded string is automatically escaped.
Now we want to fetch single row of data. First, we bind query and its parameters as before.
sql<<"SELECT name FROM users WHERE id=?",1;
But now, we store output data in single row class.
row r;
if(sql.single(r)) {
If the result of select wasn’t empty set, the condition is true and we can readout data from the row, using "iostreams" like interface.
r>>name;
Now, we want to fetch some bigger data set. In this case we use class result that stores the output data. We use:
result res; sql.fetch(res);
Now we can find out the number of the rows calling res.rows() and iterate over each row calling res.next(r).
Now, you can read the full DbiXX Library API