Database in C++? Use a wrapper

January 27, 2008

Often the database itself provides an API for its access in C/C++. But it often consists of using confusing callback functions (callbacks are fun though) and the process differs from database to database. Solution? Use a wrapper..

This wrapper seems particularly interesting.. http://www.alhem.net/project/mysql/index.html

Download the wrapper source code, compile and install.

# make
# make install

Using the database using this wrapper is as easy as:

#include <mysql/mysql.h>
#include <libmysqlwrapped.h>

int main(){
StderrLog log;
Database db(“localhost”, “dbuser”, “dbpasswd”, “mydb”, &log);
if (!db.Connected()){
printf(“Database not connected – exiting\n”);
exit(-1);
}
Query q(db);
q.get_result(“select * from player”);
while (q.fetch_row()){
long num = q.getval();
std::string name = q.getstr();
printf(“#%ld: %s\n”, num, name.c_str());
}
q.free_result();
}

Good thing is, the same code can also be used for SQLite (my fav) and ODBC too (although with different wrapper and minor modifications). Another advantage is, the wrapper is cross platform, works on both win & *nix.