FMDB (Flying Meat DB wrapper for sqlite3) for iPhone
Yesterday I started a simple application and decides to utilize FMDB wrappers sqlite3. Why?
- sqlite3 function calls are low level C, and binding between Object-C types and these C function calls is a little cumbersome and ugly (converting to/from UTF8 string and such.)
- The more code, the more clutter/change for bugs & maintenance headache. Less is more.
- I found myself effectively cut-n-pasting sqlite3 calls (init statement, bind args, call, reset statement) and as such it was crying out for a wrapper.
Here are some useful links for FMDB:
- The developer’s blog posting: http://gusmueller.com/blog/archives/2008/03/fmdb_for_iphone.html
- All the Flying Meat code (FMDB plus others) http://code.google.com/p/flycode/
- Where to get the code: http://flycode.googlecode.com/svn/trunk/fmdb/src/
I couldn’t find a pre-built library, or a project to build a library, so I ended up checking out the source from SVN and inserting the few classes into an FMDB group under my classes. The file to not include (‘cos it holds a main) is fmdb.m. This is good sample code/documentation.
BTW: Don’t forget to add the “Other Linker Flags” setting -lsqlite3 to bring in sqlite3.
Based on my brief experience with it, here is my initial review:
Pros:
- I like how simple it is to use, a nice Objective-C wrapper to sqlite3′s C API.
- I like the simple the interface to create/bind statements & result sets.
- I cannot believe there is significant performance overhead in this simple wrapper. (Yes, one access columns via name not position, but that is minor & developer friendly.)
Cons:
- Not sure how thread-safe it is. Code like [db do_something]; if ([db hadError] ) seems risky for anything but the simplest application. Maybe on iPhone this is not a problem, but feels wrong.
- What I really want is an “ActiveRecord” like implementation. Not fat/bloated, just simple binding of objects (using introspection, whatever) to/from database rows. I needed to add this on top and (as such) didn’t gain much from using FMDB verses sqlite3.
Things I’d like to know:
- I wish I knew how to get the last index (the auto-incremented primary key) of the last insert.
Summary:
I’ll keep using this for this application, and will keep an eye out to see if it develops, but I’ll also keep an eye out for other wrappers also. It seems there are a bunch of Objective-C wrappers to sqlite3, I need to see if some are iPhone friendly: