IOS SQLite 3画像の格納と読み出し


画像を保存
// Save Small Image Data by given main url 
- (void) SaveImagesToSql: (NSData*) imgData :(NSString*) mainUrl
{
    NSLog( @"
*****Save image to SQLite*****
" ); const char* sqliteQuery = "INSERT INTO IMAGES (URL, IMAGE) VALUES (?, ?)"; sqlite3_stmt* statement; if( sqlite3_prepare_v2(articlesDB, sqliteQuery, -1, &statement, NULL) == SQLITE_OK ) { sqlite3_bind_text(statement, 1, [mainUrl UTF8String], -1, SQLITE_TRANSIENT); sqlite3_bind_blob(statement, 2, [imgData bytes], [imgData length], SQLITE_TRANSIENT); sqlite3_step(statement); } else NSLog( @"SaveBody: Failed from sqlite3_prepare_v2. Error is: %s", sqlite3_errmsg(articlesDB) ); // Finalize and close database. sqlite3_finalize(statement); }

 
画像の読み込み
// Load images from data base with given image url 
- (NSData*) LoadImagesFromSql: (NSString*) imageLink
{
    NSData* data = nil;
    NSString* sqliteQuery = [NSString stringWithFormat:@"SELECT IMAGE FROM IMAGES WHERE URL = '%@'", imageLink];    
    sqlite3_stmt* statement;

    if( sqlite3_prepare_v2(articlesDB, [sqliteQuery UTF8String], -1, &statement, NULL) == SQLITE_OK )
    {
        if( sqlite3_step(statement) == SQLITE_ROW )
        {
            int length = sqlite3_column_bytes(statement, 0);
            data       = [NSData dataWithBytes:sqlite3_column_blob(statement, 0) length:length];
        }
    }

    // Finalize and close database.
    sqlite3_finalize(statement);

    return data;

}