-1

我正在更新数据库中的条目,该语句有效并且代码在数据库中更新。一旦应用程序已关闭并重新打开,但数据库尚未保存。它似乎创建了一个临时数据库,然后实际上并没有保存到应用程序正在读取的数据库中。

这是我的代码:

-(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);
    }
}

对此的任何帮助将不胜感激。

4

2 回答 2

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");
    }
}
于 2013-10-24T01:35:09.697 回答
0

当数据库在包中时,它是只读的。写入时,您需要将数据库放在文档目录中!

在这里查看接受的答案:Use and Access Existing SQLite Database on iOS

于 2013-10-24T01:35:16.087 回答