A clean and simple database api
July 15th 2010Recently, I started looking for a simple C/C++ database abstraction layer with a nice and simple API. The best I came across was libdbi.
I wanted something that did the following,
- PostgreSQL and MySQL support – because those are the 2 main databases we use at work.
- Transaction and Savepoint support.
- Support for non-blocking async calls.
- Support prepared statements.
- Do all this in a fast and simple fashion.
Unfortunately libdbi did not have some features such as support for prepared statements and support for asynchronous access. Coming from years of Perl development, I expected something along the lines of DBI and was disappointed.
I wanted to try writing something over the next weekend to see if I could come up with something simple and fast that works with PostgreSQL and MySQL.
After a few weeks of toying around, I ended up with dbic++. What started as a learning exercise ended up becoming a pet project that started to look better than many of the existing open source libraries. It also ended up outperforming most of them.
I will be releasing the code sometime next week – on github, most likely. I’ll post a link. Meanwhile here’s an example that provides a brief glimpse of the API.
#include "dbic++.h"
#include <unistd.h>
using namespace std;
using namespace dbi;
int main() {
// Handle h ("driver", "user", "password", "database", "host", "port");
Handle h ("postgresql", getlogin(), "", "dbicpp");
Statement st (h, "SELECT id, name, email FROM users WHERE id >= ? AND id < ?");
// bind and execute the statement.
st % 1L, 10L;
st.execute();
ResultRow r;
while (r = st.fetchRow())
cout << r.join("\t") << endl;
// or you can do
st.rewind();
ResultRowHash rh;
while (rh = st.fetchRowHash())
cout << rh["id"] << "\t"
<< rh["name"] << "\t"
<< rh["email"] << endl;
st.finish();
}