我试图调用存储过程C#存储过程
创建一个通用的方法我想通过一个数组
的参数传递在我有麻烦添加参数的瞬间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;
}
你想传递参数值作为字符串? – 2012-04-10 15:37:20
为什么不传递SQLParameter的数组(或列表)? – 2012-04-10 15:38:32
它失败的方式是什么?另外,为什么你使用字符串作为参数?你为什么要把名字和_same_字符串中的值解析出来?使用类似“Dictionary”这样的强类型键/值对。最后,您的异常处理将丢弃有用信息,例如堆栈跟踪和内部异常。有些东西可能无法正常工作,系统可能会告诉你它不工作的一个很好的理由,而你只是忽略它。 –
David
2012-04-10 15:39:08