5

我正在开发 iPhone 应用程序并在单击按钮时调用以下代码,它仅在第一次单击时更新我的​​数据库表。当我第二次单击它时,它给了我成功消息,但数据库表没有得到更新。

代码是:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Games.sqlite"];

NSMutableArray *arrayRandomLevel = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",nil];
for (int i = 0; i< 5; i++)
{
    NSUInteger randomIndex = arc4random() % 5;
    [arrayRandomLevel  exchangeObjectAtIndex:i withObjectAtIndex:randomIndex];
    //firstObject +=1;       
}
NSLog(@"arrayRandomLevel = %@",arrayRandomLevel);

for (int level = 0; level < 5; level++)
{
    NSString *strLevel = [@"" stringByAppendingFormat:@"%d",level+1];
    int finalLevel = [[arrayRandomLevel objectAtIndex:level] intValue];

    NSLog(@"Static level = %@, Changed level = %d",strLevel,finalLevel);

    sqlite3 *database;
    if(sqlite3_open([path UTF8String], &database) == SQLITE_OK)
    {

        NSString *cmd = [NSString stringWithFormat:@"UPDATE zquestionsdata SET zdifficultylevel = %d WHERE zanswertype = '%@' AND zquestiontype = '%@';",finalLevel,strLevel,@"Geni"];

        const char * sql = [cmd UTF8String];

        sqlite3_stmt *compiledStatement;

        if(sqlite3_prepare_v2(database, sql, -1, &compiledStatement, NULL) == SQLITE_OK)
        {
            sqlite3_step(compiledStatement); // Here is the added step.
            NSLog(@"update SUCCESS - executed command %@",cmd);
        }
        else {
            NSLog(@"update FAILED - failed to execute command %@",cmd);
        }

        sqlite3_finalize(compiledStatement);

    }
    else {
        NSLog(@"pdateContact FAILED - failed to open database");
    }

    sqlite3_close(database);

}

请帮助我或提供任何其他解决方案来每次更新表。提前致谢。

4

1 回答 1

1

更新过程将发生在

如果(sqlite3_step(语句)== SQLITE_DONE)

在那里分配的值将存储在数据库中,语句如下所示。

来自 Prepare 语句的代码如下所示

if(sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL) == SQLITE_OK)   
    {
        if(sqlite3_step(statement) == SQLITE_DONE)
        {
          //assign new values here

         }
     } 
于 2012-06-27T12:55:29.000 回答