我試圖調用存儲過程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