Iphone Database Update Problem

I am working on an iPhone application and calling the following code on my button, it updates my database table only the first time it is clicked. When I click it a second time, it gives me a success message, but the database table is not updated.

The code:

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

}

Please help me with this or provide any other solution to update the table every time. Thanks in advance.

+5
source share
1 answer

The update process will run in

if (sqlite3_step (statement) == SQLITE_DONE)

There, the assigned values ​​will be sent and stored in the database, the operator looks like the one shown above.

The code from the Prepare instructions is shown below.

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

         }
     } 
+1
source

All Articles