1

以下代码假设更新存储在字符串 dbDate 中的 Date(Primary Key) = 今天日期的行中的 2 列(HoursWorked 和 TotalEarned)。我认为我的更新字符串可能写错了。正在触发警报视图。

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

1 回答 1

1

几个问题:

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

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

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

  4. 并且,与往常一样,报告sqlite3_errmsg您的 SQLite 调用是否失败,或者您是盲目的。

因此:

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

HoursWorked我个人不会在and的数值周围使用单引号TotalEarned。您可能会考虑将日期存储为已建立的SQLite 日期格式之一。

于 2013-11-07T18:52:50.067 回答