繁体   English   中英

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

[英]How can I execute multiple transactions under same connection?

这里我的要求是这样的:

  1. 最初,我在一个事务下执行一个存储过程来插入\更新数据库中的记录。
  2. 如果由于某些问题 SP 执行失败,我必须能够在不同的事务下再次重新调用 SP。
  3. 即使 SP 的重新调用失败,我也应该在调用 function 时抛出错误。

这是示例代码。 这是处理事务和错误的正确方法,还是有更好的方法来做到这一点?

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

使用事务最简单的方法是使用System.Transaction它是一个非常简单但功能强大的 api。

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

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

你不需要 try/catch 来回滚你的事务。 如果您退出“使用”时出现异常,或者没有调用“ts.Complete”语句,您的事务将自动回滚。

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

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM