如何在同一连接下执行多个事务?

时间:2009-02-25 05:20:23

标签: c#

我的要求是这样的:

  1. 最初,我执行一个存储过程,在一次交易中在DB中插入\更新记录。
  2. 如果由于某些问题SP执行失败,我必须能够在不同的交易下再次重新调用SP。
  3. 即使重新调用SP失败,我也应该向调用函数抛出错误。
  4. 以下是示例代码。这是处理交易和错误的正确方法,还是有更好的方法来做到这一点?

    public void InsertUser(string code)
    {  
       bool bRetry=false;
       SqlTransaction transaction = null;
       Exception RetrunEx = null;
       using (SqlConnection sqlConnection = new SqlConnection(this.connectionString))
       {
          sqlConnection.Open();
    
          SqlCommand sqlCommand = new SqlCommand("InsertUser", sqlConnection);
          sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
          SqlParameter param = sqlCommand.Parameters.Add("@UserCode", SqlDbTypes.VarChar);
          param.Value = code;
    
          //Is this the proper place to begin a transaction?
          SqlTransaction transaction = connection.BeginTransaction();
          sqlCommand.Transaction = transaction;     
    
          try
          {         
              sqlCommand.ExecuteNonQuery();
              transaction.Commit();
    
          }      
          catch(SqlException SqlEx)
          {
             transaction.Rollback();
         bRetry = true;
             RetrunEx = SqlEx;
          }
          catch(Exception ex)
          {
              transaction.Rollback();
              RetrunEx = ex;
          }
    
          //Will this be treated as new transaction?
          //Is there any best way of doing this?
          transaction = connection.BeginTransaction();
          sqlCommand.Transaction = transaction;
    
          try
          { 
              if (bRetry)        
          {
                  sqlCommand.ExecuteNonQuery();
                  transaction.Commit();
                  ReturnEx = null;
              }
    
          }      
          catch(Exception Ex)
          {
             transaction.Rollback();
             RetrunEx = Ex;
          }
    
          //When both the trials fails then throw exception
          if (RetrunEx != null)
          {
              throw RetrunEx;
          }
       }
    }
    

2 个答案:

答案 0 :(得分:1)

使用交易的最简单方法是使用System.Transaction 这是一个非常简单但功能强大的api。

...
using (TransactionScope ts = new TransactionScope())
{
   //Do Transactional Work
   ...
   ...

   //Commit your transaction
   ts.Complete();
 }

你不需要try / catch来回滚你的交易。如果您退出带有例外的“使用”,或者没有调用“ts.Complete”语句,您的交易将自动回滚。

答案 1 :(得分:0)

我可能有一个方法,唯一的目的是尝试执行此存储过程。伪代码:

public bool ExecuteSP()
{
   try{
   //open connection, begin tran execture sp
   //commit transaction, return true;
   }

   catch(SqlException){

    //rollback transaction
    //return false
    }

}

然后在您的调用代码中,您可以执行以下操作:

if(!ExecuteSP() && !ExecuteSP())
{
   //throw Exception
}
相关问题