0
我有以下代碼將信息推送到數據庫。它提供了一個成功的插入,但「畫布」列(包含圖像斑點的列)爲NULL。在我已經在StackOverflow上看過其他答案之後,我已經使用了sqlite3_prepare_v2和sqlite3_bind_blob。將UIImage保存爲Blob SQLite
-(void) sendMoment: (Album *) alb moment:(Moment *) m
{
@try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
// First, test for existence of writable file:
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"pictures.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:writableDBPath];
if (!success){
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"pictures.sqlite"];
success = [fileMgr copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyy-MM-dd HH:mm:ss"];
NSString *dateString = [dateFormat stringFromDate: m.timestamp];
//add passed-in moment to the given album
sqlite3_stmt *sqlStatement;
NSData *imageData = UIImageJPEGRepresentation([m.moment firstObject], 1.0);
NSString *deleteSQL = [NSString stringWithFormat:@"DELETE FROM MomentTbl WHERE user = \"t-amkruz\""];
NSString *momentInsertSQL = [NSString stringWithFormat:@"INSERT INTO MomentTbl (momentID, albumID, title, timestamp, author, latitude, longitude, canvas) VALUES (NULL, %d, '%@', '%@', '%@', '%@', '%@', ?)", alb.ID, alb.title, dateString, @"user", m.latitude, m.longitude];
const char *query_stmt = [momentInsertSQL UTF8String];
const char *dbPath = [writableDBPath UTF8String];
int result = sqlite3_open(dbPath, &db);
if (SQLITE_OK == result) {
char *errInfo = nil;
sqlite3_prepare_v2(db, query_stmt, -1, &sqlStatement, NULL);
sqlite3_bind_blob(sqlStatement, 1, [imageData bytes], [imageData length], SQLITE_TRANSIENT);
result = sqlite3_exec(db, query_stmt, nil, nil, &errInfo);
if (SQLITE_OK == result) {
NSLog(@"Sucessful insert");
} else {
NSLog(@"Insert failed");
}
sqlite3_close(db);
}
else {
NSLog(@"Could not open database");
}
}
@catch (NSException *exception) {
NSLog(@"An exception occured: %@", [exception reason]);
}
}
同樣,我唯一有問題的部分是最後一列;正確插入每個其他列的值。我已驗證imageData
不是nil
。當我使用NSLog檢查它們時,prepare_v2語句和bind_blob語句都返回0。我真的很感激幫助!