rss
twitter
  •  

Simple Look @ Transaction in ADO.Net

| Posted in Uncategorized |

0

   // C#   
             DbTransaction tx;
             try 
             {
                 conn.Open();
                 tx = conn.BeginTransaction();
                 cmdDeleteOrders.ExecuteNonQuery();
                 cmdDeleteCustomer.ExecuteNonQuery();
                 tx.Commit();
                 conn.Close();
             }
             catch (Exception exception)
             {
                 if (tx != null)
                 {
                     tx.Rollback();
                 }
                 if (conn != null)
                 {
                     if (conn.State != ConnectionState.Closed)
                     {
                         conn.Close();
                     }
                 }
             }

The exception handling can be simplified if the previous code is refactored as shown in this next code. The using statement calls Dispose() on the transaction object. The Dispose method checks to see if there are any uncommitted changes. If there are, it rolls back the transaction

  
              // C#   
             conn.Open();
             using (DbTransaction tx = conn.BeginTransaction())
             {
                 cmdDeleteOrders.ExecuteNonQuery();
                 cmdDeleteCustomer.ExecuteNonQuery();
                 tx.Commit();
                 conn.Close();
             }

Post a comment