How to use Transaction inside Using{} block

别来无恙 提交于 2020-01-06 02:25:59

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/36234254/how-to-use-transaction-inside-using-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!