2017-11-15 14 views
0

이되는 개체 ALL하는 SqlCommand는, sqlTransaction 및 SqlDataAdapter를가 자동 (SQLConnection을 배치하는)은 "사용"블록에서 출구에 배치 또는 모든 개체를 배치 할 수있는 오브젝트 중첩 된 "using"블록으로 분리되어야합니다. 그렇지 않으면 sqlConnection 객체가 삭제 될 때 이러한 객체가 삭제되지 않습니까? 모범 사례는 무엇입니까? 객체가 IDisposable를 구현하는 경우모범 사례, SqlDataAdapter를가

public static void ExecuteDataset(string connectionString, string storedProcedure, SqlParameter[] sqlParameters = null) 
{ 
    SqlTransaction sqlTransaction = null; 

    using (SqlConnection sqlConnection = new SqlConnection(connectionString)) 
    { 
     try 
     { 
      sqlConnection.Open(); 

      SqlCommand sqlCommand = new SqlCommand(commandText, connection); 
      command.Parameters.Add("@ID", SqlDbType.Int); 

      sqlCommand.Connection = sqlConnection; 
      SqlTransaction = sqlConnection.BeginTransaction(); 
      sqlCommand.Transaction = sqlTransaction; 
      ..................................................... 
      .....................................................  

      SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(); 

       ................................ 
       ................................ 


      sqlTransaction.Commit(); 
     } 
     catch (Exception) 
     { 
      sqlTransaction.Rollback(); 
     } 
    }   
} 
+1

일반 규칙 것 : 당신이 –

+0

@ic을 완료 할 때 다음, 그것의 폐기는 IDisposable 있다면. 좋아,하지만 내 질문에 sqlConnection disposing 여부를 자동으로 모든 나머지 개체 (slqTransaction, 등) 또는 중첩 된 "블록을 사용해야합니다? – Ilan

+1

그래서 나는 대답 대신에 주석으로 썼다. :) 일반적으로 나는 사물의 내부 동작에 대해 걱정하지 않지만 특히 각 버전마다 변경되기 쉽기 때문에 걱정하지 않아도됩니다. 내가 만든 물건을 일회용으로 만들면 처분해야한다는 뜻입니다. –

답변

3

다음 using를 사용합니다. 기본 구현 세부 사항 SqlConnection 또는 SqlCommand 또는 다른 객체는 중요하지 않습니다. 시나리오에 대한

는 모범 사례는

using(var conn = new SqlConnection(...)) { 
    ... 
    using(var cmd = conn.CreateCommand(...)) { 
    ... 
    } 
    ... 
}