我正在更新数据库中的条目,该语句有效并且代码在数据库中更新。应用程序关闭后重新打开,但数据库尚未保存。它似乎创建了一个临时数据库,然后实际上没有保存到应用程序正在读取的数据库中。
这是我的代码:
-(void)updateDatabase:(int)Level andPlayer:(int)questionID{
DataClass *obj=[DataClass getInstance];
//NSFileManager *filemgr = [NSFileManager defaultManager];
NSString* Database =[NSString stringWithFormat:@"levelProgress.db"];
NSString* databaseP = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:Database];
databasePath = [[NSString alloc]initWithString:databaseP];
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &questionDB) == SQLITE_OK) {
NSString *querySQL = [NSString stringWithFormat:@"UPDATE levelProgress SET completed_questions=completed_questions+1 WHERE level=%d", obj.levelSelected];
const char *query_stmt = [querySQL UTF8String];
sqlite3_prepare_v2(questionDB, query_stmt, -1, &statement, NULL);
if(sqlite3_step(statement)==SQLITE_DONE){
NSLog(@"update worked");
}else{
NSLog(@"did not work");
}
sqlite3_finalize(statement);
sqlite3_close(questionDB);
}
}
对此的任何帮助将不胜感激。
答案 0 :(得分:1)
将数据库文件databaseP
从应用程序包复制到用户文件夹,然后进行更新。您无法更新应用程序包中的任何文件(它们始终是只读的)。
#define kDatabaseName (@"levelProgress.db")
- (void)checkAndCopyDatabaseIfNeeded
{
if (!self.databasePath)
{
// Database should be present in user sandbox at root.
self.databasePath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], kDatabaseName, nil]];
}
// Check if the file already copied/exists.
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:self.databasePath];
if(!success)
{
// Copy the file from app bundle to user sandbox (Files in app bundle can not be edited).
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:kDatabaseName];
#if DEBUG
BOOL isCopied =
#endif
[fileManager copyItemAtPath:databasePathFromApp toPath:self.databasePath error:nil];
NSAssert(isCopied, @"Problem copying database file to user document folder");
}
}
答案 1 :(得分:0)
当数据库在捆绑包中时,它是只读的。在写入数据库时,您需要将数据库放在文档目录中!
请在此处查看已接受的答案:Use and Access Existing SQLite Database on iOS