Database in C++? Use a wrapper

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.

Advertisements

One Response to Database in C++? Use a wrapper

  1. nepbabu says:

    Great stuff. 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: