Search code examples
objective-ciossqlitefmdb

NSData UIImageJPEGRepresentation not writing to SQLite fmdb


I am attempting to convert a jpeg to an nsdata object and then store that data in a blob column of an sqlite database using the fmdb wrapper.

e.g:

UIImage *img = [UIImage imageNamed:@"house.jpeg" ];
NSData *data = UIImageJPEGRepresentation(img, 1.0);
NSString *query = [NSString stringWithFormat:@"insert into t1 values (null,?)", data ];

Where t1 is created something like:

[database executeUpdate:@"create table t1(rowid integer primary key autoincrement, house blob)" ];

Ideally I would then be able to pull the data out and convert it back to a jpeg like so:

NSString *query = @"select * from t1";

FMResultSet *results = [database executeQuery:query];

while ([ results next ]) 
{

    NSData *picData = [ results dataForColumn:@"house" ];
    UIImage *housePhoto = [ UIImage imageWithData:picData ];
}

I have used this type of model for other data types like strings, etc.. with no problem. In my current attempt I am using this model with a table of string columns and 1 blob column. When I write to the database, all of the strings are stored fine, but when I try to read back the blob column like above, I get null returned for the blob column. Prior to writing to the database I double checked to see that the NSData I am writing with was not null and did contain a jpeg representation and it did. Does a known issue jump out at anyone or am I just doing something wrong externally from this?


Solution

  • This line:

    NSString *query = [NSString stringWithFormat:@"insert into t1 values (null,?)", data ];
    

    Is always going to result in this string:

    insert into t1 values (null,?)
    

    As -stringWithFormat: doesn't understand that you are trying to bind data to the "?".

    It looks like FMDatabase has an -executeQuery: method, which takes a variable number of arguments. Try this instead:

    [database executeQuery:@"insert into t1 values (null,?)", data];
    

    If you manually open the database using sqlite3, is the original JPEG data there?

    Warning: I'm accessing an ancient section in my brain, as I haven't done databases for a few years ;)