c# - 运行多个 sql 命令
问题描述
我在执行多个 sql 命令时遇到问题。我需要多次更新数据。第一个 sql 查询考虑了这两种情况 if,else; 但随后第二个和第三个 sqlcommand 将相应地出现在 if 或 else 中。问题是只有一个 sqlcommand 正常工作,即位于循环内的那些。
public void Button_Submit_Onclick(object sender, EventArgs e)
{
for (int i = 0; i < GridView2.Rows.Count; i++)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["TestDeductionsConnectionString2"].ToString();
int recordid = Convert.ToInt32(GridView2.DataKeys[i].Values[0]);
CheckBox cbox = (CheckBox)GridView2.Rows[i].FindControl("CheckBox1");
bool private1 = Convert.ToBoolean(cbox.Checked);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Update DetailCosts set private='" + private1 + "' where recordid=" + recordid;
con.Open();
if (private1==true)
{
cmd.CommandText = "Update DetailCosts set privateCost=Costs where recordid=" + recordid;
cmd.Parameters.AddWithValue("@private1", SqlDbType.Bit).Value = private1;
cmd.Parameters.AddWithValue("@recordid", SqlDbType.Int).Value = recordid.ToString();
}
else
{
cmd.CommandText = "Update DetailCosts set privateCost=0 where recordid=" + recordid;
cmd.Parameters.AddWithValue("@recordid", SqlDbType.Int).Value = recordid.ToString();
cmd.Parameters.Add("@private1", SqlDbType.Bit).Value = private1;
}
cmd.ExecuteNonQuery();
con.Close();
}
}
解决方案
You need to execute every command you want executed so you should add a
cmd.ExecuteNonQuery();
after your first query to have it also be executed.
If you want both to be executed and not if one fails you should implement transactions and wrap both queries in a transaction.
推荐阅读
- python - Tensorflow 2 未在 GPU 上运行
- excel - Excel宏删除具有连续重复列数据的行
- python - 在时间循环中使用 np.where() 以计数为条件
- python - 导入已安装的模块时出错
- c# - .xls 导入数据表缺少一些字段
- javascript - 使用 $scope 函数更改全局变量的值
- kubernetes - Kubernetes - 在 pvc "volumeMode: Block" 中指定时不调用 NodePublishVolume
- python - Python中的OpenCV4 locateROI / Offset
- ruby-on-rails - 检查对象是否属于范围的非昂贵方法
- angular - 子路径Angular8