How to save & retrieve NSdata into sqlite through FMDB

后端 未结 2 1112
栀梦
栀梦 2021-02-01 11:09

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

相关标签:
2条回答
  • 2021-02-01 11:23

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

    0 讨论(0)
  • 2021-02-01 11:35

    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];
    
    0 讨论(0)
提交回复
热议问题