在单个SqlCommand中触发多个参数化查询 [英] Firing Multiple Parameterize Quering in single SqlCommand

查看:149
本文介绍了在单个SqlCommand中触发多个参数化查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有一个命令:带有2个查询的Sqlcommand。

Hi,

I have a command: Sqlcommand with 2 queries.

SqlCommand cmd = new SqlCommand("select * from department; Select * from employee where dept=@d",con);





现在在表单的load事件中我必须填充comboBox depatment表的deptname列如:



Now at load event of form i have to populate comboBox with deptname column of depatment table like:

 SqlDataReader dr=cmd.ExecuteReader(); // Error Line 1.
 while(dr.Read())
{
  comboBox1.Items.Add(dr.GetSqlString(1));
}



第1行引发错误。我知道,我怎么解决它。

现在我想在comboxBox selecteditemChanged事件中获得第二个查询的结果,即参数化(从员工中选择* dept = @ d)。



感谢U.


Line 1 raises error. I know , How i can solve it.
Now i want to get the result of second query which is parameterize (Select * from employee where dept=@d" ) at comboxBox selecteditemChanged event.

Thank U.

推荐答案

在执行命令之前提供参数值。

Provide the parameter value before you execute the command.
cmd.Parameters.AddWithValue("@d", departmentCodeValue);


为什么要组合这两个查询?您似乎需要在不同时间获得不同的结果。

放置:

Why are you combining the two queries? You appear to need the different results at different times.
Put the:
SqlCommand cmd = new SqlCommand("select * from department;",con);



(带有相应的 con在 ExecuteReader 之前的Load事件处理程序中的)(调整传递给 GetSqlSt的参数必要时响铃



然后,在 comboBox1 选择的处理程序中更改的事件使用:


(with the appropriate con) in the Load event handler right before the ExecuteReader (adjust the argument passed to GetSqlString as necessary).

Then, in the handler for the comboBox1 selection changed event use the:

SqlCommand cmd = new SqlCommand("Select * from employee where dept=@d",con);
cmd.Parameters.AddWithValue("@d", comboBox1_selected_value);  // As OriginalGriff noted.



And执行查询并填充gridview ...


And execute the query and populate the gridview...


这篇关于在单个SqlCommand中触发多个参数化查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆