我正在将一些图像保存到我的应用程序中的 SQLite 数据库中。我使用图形 SQLite 客户端访问了数据库,它正确保存了我的图像的二进制文件。问题在于从数据库中检索它。这是它的样子:
节省
-(void)insertObject:(Object *)object
{
const char* sqliteQuery = "INSERT INTO OBJECTS (OBJECTID, OBJECTIMAGE, OBJECTNAME) VALUES (?,?,?)";
sqlite3_stmt* statement;
if( sqlite3_prepare_v2(databaseHandle, sqliteQuery, -1, &statement, NULL) == SQLITE_OK )
{
sqlite3_bind_text(statement, 1, [object.id UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_blob(statement, 2, [object.imgData bytes], [object.imgData length], SQLITE_STATIC);
sqlite3_bind_text(statement, 3, [object.name UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_step(statement);
}
else NSLog( @"SaveBody: Failed from sqlite3_prepare_v2. Error is: %s", sqlite3_errmsg(databaseHandle) );
sqlite3_finalize(statement);
}
取回
-(Object *)retrieveObjectWithID:(NSString*)id
{
NSString* sqliteQuery = [NSString stringWithFormat:@"SELECT OBJECTIMAGE,OBJECTNAME FROM OBJECTS WHERE OBJECTID = '%@'", id];
NSLog(@"sqlitequery: %@",sqliteQuery);
sqlite3_stmt* statement;
Object *object = [[Object alloc]init];
object.id = id;
if( sqlite3_prepare_v2(databaseHandle, [sqliteQuery UTF8String], -1, &statement, NULL) == SQLITE_OK )
{
if( sqlite3_step(statement) == SQLITE_ROW )
{
NSUInteger length = sqlite3_column_bytes(statement, 1);
object.imgData = [NSData dataWithBytes:sqlite3_column_blob(statement, 1) length:length];
object.name = [NSString stringWithFormat:@"%s",sqlite3_column_text(statement, 2)];
}
}
// Finalize and close database.
sqlite3_finalize(statement);
return object;
}
这是对象
@interface Object : NSObject
@property(nonatomic,strong) NSString *id;
@property(nonatomic,strong) NSString *name;
@property(nonatomic,strong) NSData *imgData;
@end