Shreedhar
Shreedhar

Reputation: 271

Saving image to SQLite

Following code i am Writing to store image in DB.

NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO slamDetailsTable (name, gender, phone,email,movie,abt,dob,smiley1,smily2,smily3,image) VALUES (\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",?)", contact.name, contact.gender, contact.phone,contact.email,contact.movies,contact.abtMe,contact.dob,contact.smiley1,contact.smiley2,contact.smiley3];
        NSLog(@"query %@",insertSQL);
        const char *insert_stmt = [insertSQL UTF8String];

        sqlite3_prepare_v2(database, insert_stmt, -1, &statement, NULL);
        sqlite3_bind_blob(statement, 1, [contact.imageData bytes], [contact.imageData length], NULL);
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            NSLog(@"Row added");
        } 

        else {
            NSLog(@"Failed to add row");
        }

Following line i am adding to get image.

NSData *imageDataFromDb = [[NSData alloc]initWithBytes:sqlite3_column_blob(statement, 11) length:sqlite3_column_int(statement, 11)];

But. imageDataFromDb showing 0 bytes.

Upvotes: 0

Views: 145

Answers (2)

ingh.am
ingh.am

Reputation: 26752

While you've asked to do something rather specific, I've always found that storing the image on the device and storing the name or location of that image in the database is a much more efficient way of doing this. Storing large images in a SQLite database can be very time consuming to get.

Upvotes: 0

Joachim Isaksson
Joachim Isaksson

Reputation: 180917

You should not use sqlite3_column_int() to get the length of the blob. The correct call to use is sqlite3_column_bytes().

If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() routine returns the number of bytes in that BLOB or string.

Upvotes: 2

Related Questions