我正在尝试利用 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 = true
会try catch
抛出DBConcurrencyException
给予Concurrency violation: the UpdateCommand affected 0 of the expected 1 records.
并且不会在表中更新/插入任何记录。
在我添加之后da.ContinueUpdateOnError = true
将da.Update()
继续没有错误但是,第一行DataTable dt
仍然不会被更新,但是,第二行dt
会被插入。
更奇怪的是,当我通过约 20 行的表调用更新时,更新完美执行,更新 2 或 3 行并插入 2 或 3 行。如果我通过一个包含 2 行的表调用更新,则会引发异常。两个不同的表具有相同的结构。