Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone Database update Issue

Tags:

sqlite

iphone

I am working on iPhone app and calling following code on my button click, its updating my Database table only on first click. When I click it second time it gives me success message but database table is not getting updated.

Code is :

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 on this or provide any other solution to update table each time. Thanks in advance.

like image 438
Rajesh Rajput Avatar asked Nov 13 '22 03:11

Rajesh Rajput


1 Answers

The Updating process will happen at

if(sqlite3_step(statement) == SQLITE_DONE)

There the values assigned will go and store in the database the statement look like the above.

code from Prepare statement is given below

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

         }
     } 
like image 157
Teja Swaroop Avatar answered Nov 16 '22 03:11

Teja Swaroop