Sqlitemm: C++ wrapper for sqlite3



As part of writing inkbook, I decided to use sqlite3 for data storage. The C/C++ API is actually a C API, and while it is object oriented and rather intuitive, it's just not C++. Considering that the API is very simple and, in particular, the subset of the API I wanted to use was very simple, I went ahead and wrote a quick wrapper.

Sqlitemm provides a C++ style interface to creation of database connections and statements (as in Connection and Statement are classes). Objects are reference counted using Glib::RefPtr so memory management is a bit easier.

You can find the project in my tracker , but heres an example of it's usage:

#include

int main(int argc, char** argv)
{
    // open a connection to a sqlite database
    Glib::RefPtr sqlite =
            sqlite::Connection::create("/path/to/db.sqlite");

    // we'll reuse this variable for different statements
    Glib::RefPtr stmt;

    // prepare a read statement
    stmt = sqlite->prepare("SELECT * FROM table_a WHERE field_a=?");

    // bind a value to one of the parameters
    stmt->bind(1,10);

    // execute the select statement
    stmt->step();

    // read out the result set
    while(stmt->hasAnotherRow())
    {
        // retrieve the first column of the result set as an integer
        int             field_a = stmt->get(0);

        // retrieve the second column of the result set as a string
        std::string     field_b = stmt->get(1);

        // retrieve the third column of the result set as a double
        double          field_c = stmt->get(2);

        // do something
    }

    // if we want to reuse the statement we need to call this
    stmt->reset();

    // prepare a second statement, note that all memory allocated for the
    // first statement is released here, because the smart pointer is
    // reassigned and the object it points to only has one outstanding reference
    stmt = m_sqlite->prepare("UPDATE table SET field_a=? WHERE field_b=?" );
    stmt->bind(1,20);
    stmt->bind(2,"something");

    // now actually execute the statement
    stmt->step();

    // note that we do not have to explicitly close the connection, when
    // the sqlite variable goes out of scope, the smart pointer will drop it's
    // reference to the underlying Connection object, and the connection
    // object will be destroyed. The databse is closed during the destructor
    // of the Connection object.
    return 0;
}

Comments


Comments powered by Disqus