Easy SQLite for the iPhone

Most applications need data, shockingly enough. I started working on my iPhone application in earnest a couple of years ago, before the availability of CoreData on the iPhone OS. The project is just now picking up some momentum, but I was pretty sure that I wanted to stay with SQLite on the device.

As it turns out, even though using SQLite with Objective-C is not too terribly complicated, I thought that there could have been a better way, and so I found Gus Mueller’s FMDB for iPhone page. He wrote an Objective-C wrapper around the SQLite calls that seems to work very well.

In order to use FMDB, you will still need to follow along with steps in other SQLite tutorials (such as this one) and do things like setting up your database file in Firefox SQLite Manager, copying the database file from the resources to the local file system on the device if needed in applicationDidFinishLaunching, and opening the database using the FMDB open method.

Once you have your database open, you can do nice things such as this:

	FMResultSet *rs = [db executeQuery:@"select * from companies where state = ?",
					   stateToSearchFor, nil];
	while ([rs next])
		NSLog(@"Name: %@", [rs stringForColumn:@"companyname"];

Just make sure that, if you want to hold your database open throughout the life cycle of your application (instead of opening and closing the database each time you read, write, or delete a record), make sure to use retain on the object returned by the FMDB open command, as the code returns an autorelease object. Or you could of course just modify the FMDB code.

Leave a Reply