0

我正在尝试利用 DataTable.Update 方法来更新 SQL 数据源。下面是执行更新的方法的代码。

string connString = "SQL connection string...this works.";
string sqlSelect = "SELECT Payment, Amount, Date, Month, StartDate, EndDate, FROM Payment";

private void updateDataSource(DataTable dt) {
    SqlDataAdapter da = new SqlDataAdapter(sqlSelect, connString);
    SqlCommandBuilder cb = new SqlCommandBuilder(da);
    int result = 0; // store the result of dt.Update

    // copy over any rows from dt that have a payment date
    DataTable temp = dt.Clone(); 
    foreach (DataRow dr in dt.Rows) {
        if (dr.ItemArray[5].ToString() != "") // if payment date is not empty
            temp.ImportRow(dr);
    }

    da.ContinueUpdateOnError = true; // this forces an insert but does not update any other records

    try {
        result = da.Update(temp);
    } catch (DBConcurrencyException dbce) {
        alertUser(
            @"There was an error updating the database.\n" +
            dbce.Message + @"\n" +
            @"The payment type id for the row was: " + dbce.Row.ItemArray[1] + @"\n" +
            @"There were " + temp.Rows.Count + @" rows in the table to be updated.\n");
    }

    if (result == temp.Rows.Count) {
        alertUser("Successful update."); // alert the user
        btnSearchCancel_Click(null, null);
    }

    // store updated data in session variable to store data between posts to server
    Session["gv"] = dt;
}

当用户单击“更新表”按钮时,将调用上述方法。
发生的事情是在我包含之前da.ContinueUpdateOnError = truetry catch抛出DBConcurrencyException给予Concurrency violation: the UpdateCommand affected 0 of the expected 1 records.并且不会在表中更新/插入任何记录。
在我添加之后da.ContinueUpdateOnError = trueda.Update()继续没有错误但是,第一行DataTable dt仍然不会被更新,但是,第二行dt会被插入。

更奇怪的是,当我通过约 20 行的表调用更新时,更新完美执行,更新 2 或 3 行并插入 2 或 3 行。如果我通过一个包含 2 行的表调用更新,则会引发异常。两个不同的表具有相同的结构。

4

1 回答 1

1

此错误仅在引用 MSDN 时发生

尝试执行 INSERT、UPDATE 或 DELETE 语句导致零个记录受到影响。

出现此错误意味着自创建 DataTable 以来数据库已更改。

错误告诉你

UpdateCommand 影响了预期的 1 条记录中的 0 条

尝试更新的记录之一不再存在或已更改并且不再与预期签名匹配。

供参考:DBConcurrencyExceptionDbDataAdapter.Update 方法多一点解释

似乎在创建 DataTable 后可能有其他一些代码正在更改数据库,或者您正在生产数据库上运行并且其他用户正在进行更改。

于 2015-06-09T19:56:54.417 回答