When I first set out to make a post about database access from C++ I was going to write about MySQL Connector/C++. But for some reason that didn’t sit well with me. After sleeping on it I realized it didn’t appeal to me because it was 1) limited to only one database backend and 2) too low-level of an API. I wanted to write about a library that supports multiple database backends and abstracts the connection details as much as possible. Ideally I wanted a library that brings you closest to SQL syntax rather than deal in C++ mechanics. So in my quest for cool and portable C++ libraries I decided to keep looking…

And then I came across SOCI – The C++ Database Access Library 🙂 It has everything I was looking for: multiple backend support (DB2, Firebird, MySQL, ODBC, Oracle, PostgresSQL, and SQLite3), and a very natural way of issuing SQL queries thanks to operator overloading and template sorcery. Even their first example is purposely left without comments because it is that easy to read and understand.

Besides a very natural way of talking to a SQL backend what I like most about it is that it allows you, in a non-intrusive way (no existing code change needed), to store and retrieve your custom data structures to and from database tables.

So I installed MySQL server on my Mac using brew package manager and started coding. Within 30 minutes I had a working example that connected to my database server, created a database and a table, inserted rows into the table from my custom Person data structure, counted the rows, retrieved a table entry with a given ID, and finally cleaned up after itself.

The only code that requires explaining is the struct type_conversion<Person>; object. It is SOCI’s mechanism of converting to and from custom data structures and requires 2 methods: from_base which converts from a set of row values to a structure, and to_base which goes the other way. The rest is self explanatory! Here’s how you can get started:

Table ‘people’ has 2 row(s)
Martin, Vorbrodt, 19800830, [email protected]

Program output.

5 Replies to “SQL database access”

  1. On the same topic, one could be interested in https://github.com/rbock/sqlpp11 which avoids having to write SQL requests.
    I don’t know SOCI, but it seems to use comma operator overloading. this is unusual enough to scare some people away (including me)!

    1. Thanks I’ll check it out. Would you be interested in rewriting my example to SQLPP11 to do the same exact queries? I would publish it and give you credit for the work 🙂

  2. i can’t build project with soci 4.0 ( i receive error: can’t see soci-config.h from header file soci-platform.h

  3. Hi, I’m using Clion IDE and have the same problem than khanh.
    Does someone know the solution?

    Thank you!

Leave a Reply