Featured image of post SQLite3 C++ Wrapper Class

SQLite3 C++ Wrapper Class

I really love sqlite databases because they are small, easy to use, performant and just do the job. The only thing they need is a file, so they are also much easier to configure, maintain and backup than heavy database solutions like MariaDB, MySQL or PostgreSQL. For big instances with plenty of workload those are clearly the better choice, but for smaller projects I prefer sqlite3, because they are just slim and easy-to-use.

Due to my affinity to Python I wrote a small C++ Wrapper Class, that should make it easier to handle sqlite3 databases in C++. In just 200 lines C++ code. It’s really easy, no Voodoo involved.

But have a look yourself at this 13 lines C++ code, that create a table, insert values and read them out.

SQLite3 db(":memory:");
db.execute("CREATE TABLE IF NOT EXISTS `test` (`id` INT PRIMARY KEY, `value` REAL);");
SQLite3Cursor cursor = db.cursor();
for(int i=0;i<10;i++) {
 cursor.execute("INSERT OR REPLACE INTO `test` (`id`,`value`) VALUES (?, ?);");
 cursor.bind(1, i);
 cursor.bind(2, i*i);
 cursor.next();
}
cursor.execute("SELECT `id`,`value` FROM `test`");
while(cursor.next()) {
  cout << cursor.fetchInt(0) << " = " << cursor.fetchFloat(1) << endl;
}

Tested in Arch Linux and in Ubuntu 16.04. And I would not see why it should not run under any other Linux distribution as well. Check it out!

Licensed under CC BY-NC-SA 4.0
Last updated on Oct 12, 2017 18:07 UTC