【问题标题】:How to use Transaction inside Using{} block如何在 Using{} 块中使用 Transaction
【发布时间】:2023-03-27 06:15:01
【问题描述】:

目前在做任何与数据库相关的代码时,我使用以下结构:

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);
}

现在我想将事务合并到上述结构中。如何使用 Using 块以正确的方式进行操作。请用正确的代码 sn-p 解释。

【问题讨论】:

    标签: c# sql transactions


    【解决方案1】:

    如果您只是读取记录 (ExecuteReader),则不需要事务,但这可能是使用 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);
    }
    

    标准方法可以写成

    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();
    }
    

    不确定异常情况下的行为或 FBConnection 对象,因此最好继续使用传统的 finally 块,在该块中以正确的顺序处理事务和连接

    【讨论】:

    • 实际上,我的示例是在 While 或 If 块内对另一个表进行一些插入操作。因此我需要使用事务进行提交或回滚。因此我要求在 using 中使用事务的正确示例阻止
    • 感谢@Steve 的回答 :)
    猜你喜欢
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    相关资源
    最近更新 更多