c# - SQL 更新语句显示 OldShippedDate == NewShippedDate(当我更改新的发货日期时)以尝试更新。抛出sql并发错误
问题描述
我正在尝试通过 C# 更改发货日期,然后过滤到 SQL Server 数据库。当我尝试更改日期时,我遇到了一个并发问题,说其他人正在访问数据库上的同一条记录。我在 C# 中使用了调试工具,并注意到旧ShippedDate
的在通过更新客户方法时显示与新的发货日期相同。我试图通过代码,似乎无法找到不正确的地方。任何帮助将不胜感激。
如上所述,我已经非常广泛地使用了调试工具,并指出原始日期被更改为新日期。然后它导致我的计数 = 0,然后引发错误。
数据库连接良好,已显示成功。
这是有问题的代码:
public static bool UpdateOrder(Orders oldOrd, Orders newOrd)
{
bool success = false; // did not update
// connection
SqlConnection connection = NORTHWNDDB.GetConnection();
// update command
string updateStatement =
"UPDATE Orders SET " +
"ShippedDate = @NewShippedDate " +
"WHERE OrderID = @OldOrderID " + // identifies order
"AND CustomerID = @OldCustomerID" + // ie. another user changed a value
" AND OrderDate= @OldOrderDate" + // before update completed
" AND RequiredDate= @OldRequiredDate" +
" AND (ShippedDate= @OldShippedDate OR " + // either equal or both are null
" ShippedDate IS NULL AND @OldShippedDate IS NULL)";
SqlCommand cmd = new SqlCommand(updateStatement, connection);
if (newOrd.ShippedDate == null)
cmd.Parameters.AddWithValue("@NewShippedDate", DBNull.Value);
else
cmd.Parameters.AddWithValue("@NewShippedDate", newOrd.ShippedDate);
cmd.Parameters.AddWithValue("@OldOrderID", oldOrd.OrderID);
cmd.Parameters.AddWithValue("@OldCustomerID", oldOrd.CustomerID);
cmd.Parameters.AddWithValue("@OldOrderDate", oldOrd.OrderDate);
cmd.Parameters.AddWithValue("@OldRequiredDate", oldOrd.RequiredDate);
if (oldOrd.ShippedDate == null)
cmd.Parameters.AddWithValue("@OldShippedDate", DBNull.Value);
else
cmd.Parameters.AddWithValue("@OldShippedDate", oldOrd.ShippedDate);
try
{
connection.Open();
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
success = true; // updated
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
connection.Close();
}
return success;
}
}
更新发货日期。我想学好这个,但到目前为止,我很挣扎。
解决方案
推荐阅读
- reactjs - Reactjs DayPickerInput 禁用天数
- javascript - 如何使用 NodeJs 从 postgresql 获取数据?
- apache-kafka - kafka 重新平衡需要很长时间才能删除过时的状态目录
- r - R中的滞后函数。计算数据框中事件的先前发生次数
- sed - 使用 sed,从特定行删除直到第一个匹配(不包括)
- php - PHP - 用星号替换字符,除非有减号
- ios - 自定义 UIButton 子类
- c# - 如何从另一个表单重新加载一个表单中的组合框项目
- javascript - 如何使用Angular中其他http服务的输出在组件中调用http get服务?
- reactjs - 带头盔的 SSR 也渲染异步元和内容?