我正在编写一段代码来存储和检索照片作为BLOB到我的sqlite数据库。
照片正在成功添加到数据库中,但是当我检索图像时,它不会显示在UIImageView中。
有人能看到这里有什么问题吗?
这是存储图像的代码:
if (sqlite3_open([[self filePath] UTF8String], &db) == SQLITE_OK) {
NSData *imgData = UIImagePNGRepresentation(TempImg); //TempImg is an UIImage instance
char *err;
NSString *sql = [NSString stringWithFormat:@"INSERT INTO 'Picture' ('Pic', 'PID') VALUES ('%@', '%@')",imgData, PID];
sqlite3_stmt *statement;
sqlite3_bind_blob(sql, 0, [imgData bytes], [imgData length], nil);
if (sqlite3_prepare_v2( db, [sql UTF8String], -1, &statement, nil) == SQLITE_OK) {
if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err)!= SQLITE_OK )
{sqlite3_close(db);}
else{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Success" message:@"The Photo have been successfully added." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
sqlite3_close(db);
}
}
}
这是检索代码:
if (sqlite3_open([[self filePath] UTF8String], &db) == SQLITE_OK) {
NSString *sql = [NSString stringWithFormat:@"SELECT * FROM Picture Where PicID = '14'"];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2( db, [sql UTF8String], -1, &statement, nil) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW)
{
char *field1 = (char *) sqlite3_column_text(statement, 0);//the name of the picture
NSString *field1Str = [[NSString alloc] initWithUTF8String: field1];
field.text= field1Str;
NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(statement, 1) length:sqlite3_column_bytes(statement, 1)];
if (data==nil) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"NULL" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
UIImage *newImage = [UIImage imageWithData:data];
[Img setImage:newImage];//Img is a UIImageView instance
}
sqlite3_close(db);
}
}
问题是,Img UIImageView没有显示任何内容。