Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save & retrieve NSdata into sqlite through FMDB

How can I save NSData into sqlite, I am using FMDB wrapper for saving data.

Below is the code which I have tried so far
For saving

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model.expertArray];; 
NSString *query = [NSString stringWithFormat:@"insert into save_article values ('%@','%@','%@','%@','%@','%@')",
                       model.Id, model.title, model.earliestKnownDate, data, model.excerpt,model.image_url];

For Retriving

while([results next]) {
  NSData *data = [results dataForColumn:@"experts"];
        NSMutableArray *photoArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
 }     

I have tried both datatype blob & text but no luck so far, can anybody guide me how to do it?

like image 639
DAMM108 Avatar asked Mar 06 '14 19:03

DAMM108


People also ask

What is the 30 day rule?

With the 30 day savings rule, you defer all non-essential purchases and impulse buys for 30 days. Instead of spending your money on something you might not need, you're going to take 30 days to think about it. At the end of this 30 day period, if you still want to make that purchase, feel free to go for it.

What's the 50 30 20 budget rule?

What is the 50/30/20 rule? The 50/30/20 rule is an easy budgeting method that can help you to manage your money effectively, simply and sustainably. The basic rule of thumb is to divide your monthly after-tax income into three spending categories: 50% for needs, 30% for wants and 20% for savings or paying off debt.


1 Answers

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 :)

like image 92
DAMM108 Avatar answered Nov 02 '22 20:11

DAMM108