我有一个应用程序,允许您将项目添加到列表中(从表格视图),当用户单击相应项目旁边的添加按钮时,它会调用以下+(void)addItem方法。一切正常,但经过大量测试(60-70背对背插入导致它返回SQL错误代码“无法打开数据库文件”,应用程序必须重新启动。任何想法?谢谢!
+(void)addItem:(NSString *)dbPath{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *oldTrip = [prefs objectForKey:@"selectedList"];
NSString *table = @"The Table";
NSString *name = [prefs objectForKey:@"SelectedAddItem"];
NSString *countStr = @"1";
NSString *doneStr = @"No";
NSString *noteStr = @"None";
NSString *orderStr = @"15";
sqlite3 *database;
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sqlStr = [[NSString stringWithFormat:@"Insert into '%@' Values (null,?,?,?,?,?,?)",oldTrip]UTF8String];
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(database, sqlStr, -1, &compiledStatement, NULL) == SQLITE_OK){
sqlite3_bind_text(compiledStatement, 0,[oldTrip UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 1,[name UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2,[table UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 3,[countStr UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 4,[doneStr UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 5,[noteStr UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 6,[orderStr UTF8String], -1, SQLITE_TRANSIENT);
}
if(sqlite3_step(compiledStatement) != SQLITE_DONE ) {
NSString* messageString = [NSString stringWithFormat: @"%s\n\nPlease contact the developer if this error persists", sqlite3_errmsg(database)];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error inserting" message:messageString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
} else {
sqlite3_reset(compiledStatement);
sqlite3_finalize(compiledStatement);
}
}
sqlite3_close(database);
}
要获取数据库信息,我使用:
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"ListDatabase.sql"];
}
答案 0 :(得分:0)
如果仅在高负载下发生,您可能希望尝试打开数据库文件,而不是为每个操作打开和关闭它。我对SQLite不太熟悉,但你也可以通过每次重置绑定来重用编译语句(如果你在reset
之前你不需要调用finalize
不打算重用声明)。
也许您可以在视图控制器的viewDidLoad
和viewDidUnload
方法中打开和关闭数据库?