我有一些代码可以添加数据库的票证。我可以添加很好,但是当我在数据库中尝试更新现有票证时,我只能更新一次,然后每次更新失败。如果我重新启动应用程序,我可以再次更新一次,然后每次更新尝试失败。有人可以帮我找到导致这种情况的原因。这是我添加/更新数据库的代码。
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_ticketDB) == SQLITE_OK)
{
//first I check to see if ticket already exists
NSString *insertSQL = [NSString stringWithFormat:@"SELECT * FROM tickets WHERE ticketnum = \'%@\'", globalData.ticket];
int rc = sqlite3_prepare_v2(_ticketDB, [insertSQL UTF8String], -1, &statement, nil);
if (rc == SQLITE_OK) {
//Based on if ticket exists, I either update or insert new row
if (sqlite3_step(statement) == SQLITE_ROW) {
insertSQL = [NSString stringWithFormat:@"UPDATE tickets SET shippername = \'%@\' WHERE ticketnum = \'%@\'", globalData.shipperName, globalData.ticket];
}
else{
insertSQL = [NSString stringWithFormat:@"INSERT INTO TICKETS (ticketnum, shippername) VALUES (\"%@\", \"%@\")", globalData.ticket, globalData.shipperName];
}
}
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_ticketDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(@"Added/Updated");
} else {
NSLog(@"Failed to add/update ticket to db");
}
sqlite3_finalize(statement);
sqlite3_close(_ticketDB);
}
答案 0 :(得分:1)
[来自Googie的评论:]
您永远不会完成“SELECT”语句,而是使用相同的变量准备另一个语句来存储它。旧语句不会自动完成,它只是在内存中丢失,可能就是更新此行时保持“UPDATE”语句,因为该行被“SELECT”语句锁定。
再添加一个
sqlite3_finalize(statement);
前
sqlite3_prepare_v2(_ticketDB, insert_stmt, -1, &statement, NULL);