如何动态地将多个参数传递给SqlCommand。 [英] How to pass multiple parameter dynamically to the SqlCommand.
本文介绍了如何动态地将多个参数传递给SqlCommand。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想动态地将多个参数(cmd.Parameters.AddWithValue)传递给SqlCommand。
例如: -
1.有时我想传递单个参数。
2.有时参数可能是2或更多。
注意: - 我想根据条件在一个函数中传递多个参数。
这是代码。
-----------------
Hi,
I want to pass multiple parameters (cmd.Parameters.AddWithValue) to the SqlCommand dynamically.
For example:-
1. some times i want to pass single parameters.
2. some times Parameters may be 2 or more.
Note:- I want to pass multiple parameters in a single Function based on condition.
Here is the Code.
-----------------
private DataSet SelectQuery(string query, string param)
{
try
{
using (con)
{
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@Emp_No", param); // here i want to pass parameters dynamically to the SqlCommand.
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
con.Close();
return ds;
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
推荐答案
你可以像这样改变你的方法
You Can Change your method like this
private DataSet SelectQuery(string query, params IDataParameter[] sqlParams)
{
try
{
var con=new SqlConnection(connectionString);
using (con)
{
con.Open();
var cmd = new SqlCommand(query, con);
if (sqlParams != null)
{
foreach (IDataParameter para in sqlParams)
{
cmd.Parameters.Add(para);
}
}
using (var sda = new SqlDataAdapter())
{
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
con.Close();
return ds;
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
并传递多个参数
And Pass multiple parameters
这篇关于如何动态地将多个参数传递给SqlCommand。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文