我尝试新的东西(对我来说,至少),而不是具有调用单个存储过程的特定功能(数据访问功能与存储过程的比率为1:1),我'我试图编写传递存储过程名称的通用函数,以及参数名称和参数值的字符串数组作为参数。
例如:
public DataTable CallQuery(string spName, string[] paramNames, string[] paramValues, string connString)
{
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(connString);
try
{
//create a command and assign it to the passed stored procedure name
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn; // new SqlConnection(connString); ;
cmd.CommandText = spName;
//add any and all parameters to the command
for(int i = 0; i < paramNames.Length; i++)
{
SqlParameter temp = new SqlParameter(paramNames[i], paramValues[i]);
cmd.Parameters.Add(temp);
//cmd.Parameters.AddWithValue(paramNames[i], paramValues[i]);
}
//get the data and return it
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
catch (Exception)
{
return dt;
}
}
不幸的是,出于某种原因,当我用参数值调用此函数时(即paramNames [0] =&#34; @ Provider&#34;和paramValues [0] =&#34; AT&amp; T&#34;)并进行数据库调用,我捕到一个异常,说存储过程期望参数@Provider
。
我已经介入并验证参数是否正在添加其值,但我仍然得到相同的异常。我在这里错过了一些简单的东西吗?
我传入字符串数组的原因是因为每个存储过程可能有0到5个参数(到目前为止......)。
答案 0 :(得分:2)
尝试为参数指定类型。但是,最重要的是确保你这样做:
cmd.CommandType = CommandType.StoredProcedure;