C#、SQL中的事務


c#方法一:
       TransactionOptions transactionOption = new TransactionOptions(); //設置事務隔離級別 transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; // 設置事務超時時間為60秒 transactionOption.Timeout = new TimeSpan(0, 0, 60); using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, transactionOption)) { int id = 0; try {
            //do something
scope.Complete(); } catch (Exception ex) { throw ex; } finally { scope.Dispose(); } }

 

 c#方法二:  SqlTransaction   sqlTransaction   =   sqlConnection.BeginTransaction();   
         SqlCommand   sqlCommand   =   new   SqlCommand();  
         sqlCommand.Transaction = sqlTransaction;
         sqlTransaction.Commit();  
         try   
          {   
            //   利用sqlcommand進行數據操作   
              ...   
            //   成功提交   
            sqlTransaction.Commit();   
          }   
          catch(Exception   ex)   
          {   
              //   出錯回滾   
            sqlTransaction.Rollback();   
          }  
           finally   
              {   
                    cnn.Close();   
                    trans.Dispose();   
                    cnn.Dispose();   
               }    

 

  BEGIN TRANSACTION
  /*--定義變量,用於累計事務執行過程中的錯誤--*/
  DECLARE @errorSum INT
  SET @errorSum=0 --初始化為0,即無錯誤
  /*--轉賬:張三的賬戶少1000元,李四的賬戶多1000元*/
   
  SET @errorSum=@errorSum+@@error --累計是否有錯誤
     IF @errorSum<>0 --如果有錯誤
  BEGIN
  print '交易失敗,回滾事務'
  ROLLBACK TRANSACTION        --回滾
  END
  ELSE
  BEGIN
  print '交易成功,提交事務,寫入硬盤,永久的保存'
  COMMIT TRANSACTION        --執行修改保存
  END
  GO
  print '查看轉賬事務后的余額'
  GO
SQL中

 參考: http://www.cnblogs.com/Garden-blog/archive/2011/04/21/2023417.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM