【发布时间】:2012-04-10 15:34:45
【问题描述】:
我正在尝试创建一个用于调用存储过程的通用方法
我想通过数组传入参数
目前我无法将参数添加到 SqlCommand
这就是我目前所拥有的
谁能给点建议
谢谢
西蒙
调用方法
string[] paramNames = new string[1];
paramNames[0] = "@date = 2012-1-1";
string err="";
WriteToDatabase("exec LoadData", CommandType.StoredProcedure, paramNames, out err);
方法
public static bool WriteToDatabase(
string sql,
CommandType commandType,
string[] paramNames,
out string errorText)
{
bool success = false;
errorText = "";
try
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
List<SqlParameter> parameters = new List<SqlParameter>();
foreach (string paramName in paramNames)
{
parameters.Add(new SqlParameter() { ParameterName = paramName });
}
using (SqlCommand command = new SqlCommand()
{
Connection = connection,
CommandText = sql,
CommandType = commandType,
Parameters = parameters
})
command.ExecuteNonQuery();
connection.Close();
}
}
catch (SqlException sex)
{
log.Error("QueryDatabase SQLexception:" + sex.Message);
}
catch (Exception ex)
{
log.Error("QueryDatabase exception:" + ex.Message);
}
return success;
}
【问题讨论】:
-
您想将参数值作为字符串传递??
-
为什么不只传递一个 SQLParameter 数组(或列表)?
-
以什么方式失败?另外,为什么要使用字符串作为参数?为什么要将名称和值放在要解析的 same 字符串中?对强类型键/值对使用
Dictionary<TKey,TValue>之类的东西。最后,您的异常处理会丢弃有用的信息,例如堆栈跟踪和内部异常。有可能某些东西不工作,系统向你提供了一个很好的理由为什么它不工作,而你只是忽略了它。
标签: c# .net stored-procedures