我有以下代码将信息推送到数据库。它提供了一个成功的插入,但"画布"列(包含图像blob的列)为NULL。我已经在我在StackOverflow上看到的其他答案之后模拟了我对sqlite3_prepare_v2和sqlite3_bind_blob的使用。
-(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。我真的很感激帮助!
答案 0 :(得分:0)
事实证明我需要用以下代码替换exec语句(以及后续的if语句):
if(sqlite3_step(sqlStatement) == SQLITE_OK){
NSLog(@"Sucessful insert");
}
else {
NSLog(@"Insert failed");
}
希望这有助于其他人。