行不更新sqlite3

时间:2013-11-07 18:34:46

标签: ios sqlite

以下代码用于更新日期(主键)=今天日期的行中的2列(HoursWorked和TotalEarned),该日期存储在字符串dbDate中。我认为我的更新字符串可能写错了。警报视图正在被触发。

        sqlite3_stmt *newstatement;
        sql =[NSString stringWithFormat:@"UPDATE HourLog SET HoursWorked = '%@', TotalEarned = '%@' WHERE Date ='%@'", HoursWorked, TotalEarned, dbDate];
        if(sqlite3_prepare_v2(db, [sql UTF8String], -1, &newstatement, nil)==SQLITE_OK){

            NSLog(@"details updated");

            UIAlertView *alertDialog;
            alertDialog = [[UIAlertView alloc]
                           initWithTitle:@"Title"
                           message:@"Details Updated!"
                           delegate:nil
                           cancelButtonTitle:@"Close"
                           otherButtonTitles: nil];
            [alertDialog show];
            sqlite3_step(newstatement);
        }

        sqlite3_finalize(newstatement);
        sqlite3_close(db);

1 个答案:

答案 0 :(得分:1)

有几个问题:

  1. UPDATE语法不正确。要更新的各个字段必须用逗号分隔,而不是单词AND

  2. 在确认sqlite3_step的结果之前,您可能不应该报告更新成功。

  3. 如果您没有点击WHERE子句,我可能会建议您确定更新了多少行,以便确认WHERE子句成功。

  4. 并且as always,如果您的SQLite调用失败,或者您正在盲目飞行,则报告sqlite3_errmsg

  5. 因此:

    sqlite3_stmt *statement;
    
    int originalTotalCount = sqlite3_total_changes(db);
    
    NSString *sql = [NSString stringWithFormat:@"UPDATE HourLog SET HoursWorked = %@ , TotalEarned = %@ WHERE Date='%@'", HoursWorked, TotalEarned, dbDate];
    
    if (sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil) != SQLITE_OK) {
        NSLog(@"%s: prepare failed: %s", __FUNCTION__, sqlite3_errmsg(db));
    } else {
        if (sqlite3_step(statement) != SQLITE_DONE) {
            NSLog(@"%s: step failed: %s", __FUNCTION__, sqlite3_errmsg(db));
        } else {
            int rowsUpdated = sqlite3_total_changes(db) - originalTotalCount;
    
            NSString *message;
    
            if (rowsUpdated == 1)
                message = @"Updated one row";
            else if (rowsUpdated == 0)
                message = @"No rows updated";
            else
                message = [NSString stringWithFormat:@"Updated %d rows", rowsUpdated]; // should never happen
    
            NSLog(@"%@", message);
    
            UIAlertView *alertDialog = [[UIAlertView alloc] initWithTitle:nil
                                                                  message:message
                                                                 delegate:nil
                                                        cancelButtonTitle:@"Close"
                                                        otherButtonTitles:nil];
            [alertDialog show];
        }
    
        sqlite3_finalize(statement);
    }
    

    我个人不会在HoursWorkedTotalEarned的数值周围使用单引号。您可以考虑将日期存储在已建立的SQLite date formats中。