是否需要單獨處理SqlConnection以及SqlCommand?是否需要配置SqlConnection以及SqlCommand?
我在做一個應用程序的一些維護工作,發現下面的代碼:
public void CallStoredProc(string storedProcName)
{
using (SqlCommand command = new SqlCommand(storedProcName, CreateConnection()))
{
command.CommandType = CommandType.StoredProcedure;
command.Connection.Open();
// Additional code here.
command.ExecuteNonQuery();
}
}
請問這樣清理關閉SqlConnection正確,正常情況下,以及是否存在錯誤?或者我們必須將代碼更改爲如下所示:
public void CallStoredProc(string storedProcName)
{
using (SqlConnection connection = CreateConnection())
{
using (SqlCommand command = new SqlCommand(storedProcName, connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Connection.Open();
// Additional code here.
command.ExecuteNonQuery();
}
}
}
你會在這裏得到答案http://stackoverflow.com/questions/12603093/can-you-dispose-of-multiple-objects-within-a-using-block http://stackoverflow.com/問題/ 9396064 /使用語句與 - 多變量 – andy