Tuesday, April 10, 2012

Inserting and Deleting Data using FMDB


I have been using FMDB to manage the Star Traders RPG database files in iPhone.

There are two ways to run the -(void) executeUpdate; method, as outlined here:

http://www.icodeblog.com/2011/11/04/simple-sqlite-database-interaction-using-fmdb/

The page that got me started was this -- the key is the "open" method

Inserting And Deleting Data

Inserting data using sqlite is very straight forward. You can either build your strings and pass them in directly OR use the sqlite format using “?’s” and letting fmdb do the work. Below is an example of each:
// Building the string ourself
NSString *query = [NSString stringWithFormat:@"insert into user values ('%@', %d)",
@"brandontreb", 25];
[database executeUpdate:query];
 
// Let fmdb do the work
[database executeUpdate:@"insert into user(name, age) values(?,?)",
@"cruffenach",[NSNumber numberWithInt:25],nil];
Generally, the second route is preferred as fmdb will do some of the sanitizing for your (such as add slashes to single quotes).
Now that we have some data in our database, let’s delete it. The following code will delete all users with an age of 25:
[database executeUpdate:@"delete from user where age = 25"];
And that should remove both of the records that we inserted.

No comments: