msm
msm

Reputation: 69

How to use Transaction inside Using{} block

At present while doing any database related code i use the following structure:

try
{
   using(FBConnection con = new FBConnection('connectionstringhere'))
   {
     con.Open();
     using(FBCommand cmd = FBCommand("qryString",con))
     {
       cmd.Parameters.Add("paramSql", FbDbType.Date).Value ="somevalue";
       cmd.CommandType = CommandType.Text;
       using(FBDatareader rdr = cmd.ExecuteReader())
       {
         while(rdr.Read())
         {
          //some code here
         } 
       }
     }
   }
}
catch(FBException ex)
{
  MessageBox.Show(ex.Message);
}

Now i want to incorporate Transaction in the above structure.How do i do it proper way using Using block. Please explain with proper code snippet.

Upvotes: 1

Views: 1399

Answers (1)

Steve
Steve

Reputation: 216293

You don't need a Transaction if you are just reading records (ExecuteReader) however this could be an approach using the TransactionScope class

try
{
   using(TransactionScope scope = new TransactionScope())
   using(FBConnection con = new FBConnection('connectionstringhere'))
   {
     con.Open();
     ...
     scope.Complete();
   }
}
catch(FBException ex)
{
   // No rollback needed in case of exceptions. 
   // Exiting from the using statement without Scope.Complete
   // will cause the rollback
  MessageBox.Show(ex.Message);
}

The standard approach could be written as

FBTransaction transaction = null;
FBConnection con = null;
try
{
   con = new FBConnection('connectionstringhere');
   con.Open();
   transaction = con.BeginTransaction();
   ...
   transaction.Commit();
}
catch(FBException ex)
{
    MessageBox.Show(ex.Message);
    if(transaction!=null) transaction.Rollback();
}
finally
{
    if(transaction != null) transaction.Dispose();
    if(con != null) con.Dispose();
}

Not sure about the behavior or the FBConnection object in case of exceptions so better going on a traditional finally block in which you dispose the transaction and the connection in the correct order

Upvotes: 1

Related Questions