小编典典

在“使用”块中,是否在返回或异常时关闭SqlConnection?

c#

第一个问题:
说我有

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    string storedProc = "GetData";
    SqlCommand command = new SqlCommand(storedProc, connection);
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));

    return (byte[])command.ExecuteScalar();
}

连接是否关闭?因为从技术上讲,我们永远都无法}return以前那样走到最后。

第二个问题:
这次我有:

try
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        int employeeID = findEmployeeID();

        connection.Open();
        SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));
        command.CommandTimeout = 5;

        command.ExecuteNonQuery();
    }
}
catch (Exception) { /*Handle error*/ }

现在,说出try我们中的某个地方,我们得到了一个错误,它被抓住了。连接仍然关闭吗?再次,因为我们跳过的其余代码,try直接进入catch语句。

我在using工作方式上是否太过线性思考?即,Dispose()当我们离开using示波器时,是否会被简单调用?


阅读 244

收藏
2020-05-19

共1个答案

小编典典

  1. 是。

无论哪种方式,退出using块(通过成功完成或错误退出)时,它都会关闭。

尽管我认为这样组织起来会 更好 ,因为即使要以后支持它的新维护程序员,也可以很容易地看到要发生的情况,这很容易:

using (SqlConnection connection = new SqlConnection(connectionString)) 
{    
    int employeeID = findEmployeeID();    
    try    
    {
        connection.Open();
        SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));
        command.CommandTimeout = 5;

        command.ExecuteNonQuery();    
    } 
    catch (Exception) 
    { 
        /*Handle error*/ 
    }
}
2020-05-19