c# - SQLCommand批量更新查询

标签 c# asp.net asp.net-mvc asp.net-mvc-4 c#-4.0

我写了如下代码:

 for (int i = 0; i < ListToUpdate.Count; i = i + 500)
 {
   SqlCommand command = new SqlCommand();
   command.Connection = new SqlConnection("Data Source=.;Initial Catalog=mydb;Integrated Security=SSPI");
   command.Connection.Open();
   var batchList = ListToUpdate.Skip(i).Take(500);
   for (int j = 0; j < batchList.Count(); j++)
   {
      command.CommandText += string.Format("update mytable set column=@s_id{0} where columnid = @id{0};", j);
      command.Parameters.AddWithValue("@s_id" + j, ListToUpdate[j].QuantitySoldTotal);
      command.Parameters.AddWithValue("@id" + j, ListToUpdate[j].ItemId);
   }
   command.ExecuteNonQuery();
   command.Connection.Close();
 }

这应该批量更新我的表,但奇怪的是查询只在第一次执行...

如果列表中有 1500 个项目,只有第一批得到更新...而其他的则不会...

我在这里做错了什么???

最佳答案

是否每次迭代都要关闭并重新打开连接?一旦打开连接,只需在每次批量更新后使用

创建一个新的 sql 命令文本
command.CommandText = CommandType.Text;

我建议这个 -

SqlCommand command = new SqlCommand();
command.Connection = new SqlConnection("Data Source=.;Initial Catalog=mydb;Integrated Security=SSPI");
command.Connection.Open();

for (int i = 0; i < ListToUpdate.Count; i = i + 500) {
    var batchList = ListToUpdate.Skip(i).Take(500);
    for (int j = 0; j < batchList.Count(); j++) {
        command.CommandText += string.Format("update mytable set column=@s_id{0} where columnid = @id{0};", j);
        command.Parameters.AddWithValue("@s_id" + j, batchList[j].QuantitySoldTotal);
        command.Parameters.AddWithValue("@id" + j, batchList[j].ItemId)
    }
    command.ExecuteNonQuery();
    command.CommandText = CommandType.Text;
}
command.Connection.Close();

从生成的新列表中选择属性,例如 batchList[j]

关于c# - SQLCommand批量更新查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43609557/

相关文章:

asp.net-mvc - Asp.net MVC 3 中的单元测试模型更改

c# - InternetExplorer COMException : System. Runtime.InteropServices.COMexception: RPC 服务器不可用

c# - 我应该为包含 Thread 的类实现 IDisposable

c# - 在 ASP.NET MVC 中连接查询字符串

asp.net-mvc - 从区域调用部分 View

ASP.NET:如何访问中继器生成的表单输入元素?

c# - 如果我需要一个 bool 来将选项也设置为 null,那么我最好使用可空 bool 还是自定义枚举?

C# 射弹模拟器 - 将速度应用于射弹物理的 X 位置

c# - 这是在 WebMatrix 中设置和维护 session 变量的最佳方式吗?

javascript - 在 javascript 条件中使用 asp.net 内联标记