How to save & retrieve NSdata into sqlite through FMDB How to save & retrieve NSdata into sqlite through FMDB sqlite sqlite

How to save & retrieve NSdata into sqlite through FMDB


Below is the Snippet for all who may face the same issue while inserting NSData to Sqlite using FMDB.

In my Case I wanted to store NSArray in Sqlite So i first convert the NSArray into NSData & then store it in Sqlite.

Converting NSArray into NSData

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:YourNSarray];;

Saving NSData into Sqlite

[database executeQuery:@"insert into save_article values (?,?,?,?,?,?)", model.Id, model.title, model.earliestKnownDate, data, model.excerpt,model.image_url];

Note:- Don't build a query using stringWithFormat[below is the code which you should not use]:. Thanks to @rmaddy & @hotlicks for pointing me to this :)

NSString *query = [NSString stringWithFormat:@"insert into user values ('%@', %d)",@"brandontreb", 25];[database executeUpdate:query];

and now the last step i.e retrieving NSData back to NSArray

NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:[database dataForColumn:@"yourcololumname"]];

Hope this will help the needy & beginner :)


Don't build a query using stringWithFormat:. This is a bad idea for several reasons.

Use the executeQuery method where you put a ? for each value to be bound to the query.

Something like this:

[database executeQuery:@"insert into save_article values (?,?,?,?,?,?)", model.Id, model.title, model.earliestKnownDate, data, model.excerpt,model.image_url];