Thursday, May 14, 2009

Easy SQLite wrapper for the iPhone

SQLite is great. It is small, fast and easy to set up. However, if you are writing an iPhone app that needs it, you're in for a bit of learning. You will need to learn what API calls to make and when to make them, usually by going over example code and using trial and error. I am introducing an open source SQLite C++ wrapper that will allow you to use the database without having to learn the SQLite API. It may save you several days of work.

The wrapper is just two C++ files, has a MIT style license and is platform independent so it's not just for iPhone. You will still need to learn the quirky SQLite SQL syntax however.

You can download it here.

Creating a database and table
#include "sdsqlite.h"

void create_db(void)
{
sd::sqlite database("mydb.db");
database << "create table if not exists work (first_name text, last_name text, hours real)";
}


Database insertion
#include "sdsqlite.h"

struct work_data { char* first; char* last; float hours; };

work_data wdata[] = {
{"Joe", "Smith", 2.5},
...
};

void insert_rows(void)
{
try
{
sd::sqlite database("mydb.db"); // open the db with the table already created

sd::sql insert_query(database); // build an sql query
insert_query << "insert into work (first_name, last_name, hours) VALUES(?, ?, ?)";

database << "begin transaction";// create a transaction for speed

// insert data (sdsqlite will auto-detect data type and execure query)
for(int i=0;i<sizeof(wdata)/sizeof(work_data);++i)
insert_query << wdata[i].first << wdata[i].last << wdata[i].hours;

database << "commit transaction";// complete transaction
}
catch(sd::db_error& err)
{
// do something with error
}
}


Database extraction
#include "sdsqlite.h"

void extract_name(const std::string& name)
{
try
{
sd::sqlite database("mydb.db"); // open the db with the table already created

// select all names that begin with the contents of the "name" variable
sd::sql select_query(database);
select_query << "select first_name, last_name, hours from work where first_name like ?" << name + '%';

// extract the matching rows
float hours;
std::string first, last;
while(select_query.step())
{
select_query >> first >> last >> hours;

// do something with the data
}
}
catch(sd::db_error& err)
{
// do something with error
}
}

0 comments:

Post a Comment