【问题标题】:how to do error handling with using statements in C#如何在 C# 中使用 using 语句进行错误处理
【发布时间】:2011-11-02 12:10:34
【问题描述】:

我试图从多个数据库表中删除记录。对于错误处理,我正在使用如下所示的 try/catch 块。

try
{
    using (SqlCeConnection oConn = new SqlCeConnection(ConnectionString))
    {
        oConn.Open();
        using (SqlCeTransaction transaction = oConn.BeginTransaction())
        {
            //delete from multiple tables using ADO.NET
            transaction.Commit();
        }
    }
}
catch
{
   //error handling
}

问题是当引发异常时,事务不会回滚。在阅读多个论坛时,我的结论是“使用”语句应该处理事务和连接。处置后,应回滚未提交的事务。

谁能告诉我我做错了什么。

【问题讨论】:

  • try-catch 块移动到using
  • @L.B 只要异常发生在提交行之前,那应该没有什么不同。表面上代码看起来不错,但它的作用取决于处理代码在 SqlCe DLL 中是如何实现的,我只能假设它做了常识性的事情并回滚事务。
  • 我讨厌听起来很愚蠢,但是......你怎么知道你的交易正在被提交,尽管从未点击过 transaction.Commit?
  • 您不能使用oConnusing 之外进行回滚
  • SqlTransaction 的处置按您的想法工作(使用回滚),并且在包装在 using 中时将始终被调用。除非在提交后发生异常,否则您所描述的不应发生。你确定不是这样吗?

标签: c# ado.net transactions error-handling using-statement


【解决方案1】:

我的猜测是您没有设置SqlCeCommandTransaction 属性(您没有显示)。

try
{
    using (SqlCeConnection oConn = new SqlCeConnection(ConnectionString))
    {
        oConn.Open();
        using (SqlCeCommand command = oConn.CreateCommand())
        {
            using (SqlCeTransaction transaction = oConn.BeginTransaction())
            {
               command.Transaction = transaction;
               //delete from multiple tables using ADO.NET using command
               transaction.Commit();
            }
        }

    }
}
catch
{
   //error handling
}

SqlCeCommand 不会自动加入事务,您必须明确设置它。据我所知,TransactionDispose() 应该回滚它,但您可以自己调用 Rollback(),就像其他人建议的那样。

【讨论】:

    【解决方案2】:
    try 
    {
      using (SqlCeConnection oConn = new SqlCeConnection(ConnectionString))
      {
        oConn.Open();
    
        using (SqlCeTransaction transaction = oConn.BeginTransaction())
        {
            try
            {
              //delete from multiple tables using ADO.NET
              transaction.Commit();
            }
            catch 
            {
               transaction.Rollback();
               throw;
            }
        }
      }
    }
    catch (Exception e)
    {
      // do Exception handling here
    }

    【讨论】:

      【解决方案3】:

      为了安全起见:

          using (SqlCeTransaction transaction = oConn.BeginTransaction())
          {
              try
              {
                //delete from multiple tables using ADO.NET
                transaction.Commit();
              }
              catch
              {
                 transaction.Rollback();
                 throw;
              }
          }
      

      我找不到说明事务默认回滚的直接文档。

      【讨论】:

        【解决方案4】:

        基本上你的try{...} catch{} 块是在错误的地方。它应该在 using 语句中,最好在 transaction.Commit 周围

        【讨论】:

          猜你喜欢
          • 2021-10-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-27
          • 2014-04-04
          • 1970-01-01
          • 2020-03-06
          • 1970-01-01
          相关资源
          最近更新 更多