是否需要单独处理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