「using」ブロックでは、SqlConnection は戻りまたは例外時に閉じられますか? 質問する

「using」ブロックでは、SqlConnection は戻りまたは例外時に閉じられますか? 質問する

最初の質問:
持っていると言う

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

2番目の質問:
今回は以下のものがあります:

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?

ベストアンサー1

  1. はい
  2. はい。

いずれにしても、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*/ 
    }
}

おすすめ記事