我正在开发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);
}
请帮助我,或者每次都提供更新表的任何其他解决方案。 提前谢谢。
答案 0 :(得分:1)
更新过程将在
进行if(sqlite3_step(statement)== 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
}
}