2008-12-04 70 views
2

我在問自己是否有可能檢查ADO.NET中是否可以回滾當前事務。ADO.NET檢查是否可能回滾

在MSDN提出以下建議執行:

private static void ExecuteSqlTransaction(string connectionString) 
{ 
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    { 
     connection.Open(); 

     SqlCommand command = connection.CreateCommand(); 
     SqlTransaction transaction; 

     // Start a local transaction. 
     transaction = connection.BeginTransaction("SampleTransaction"); 

     // Must assign both transaction object and connection 
     // to Command object for a pending local transaction 
     command.Connection = connection; 
     command.Transaction = transaction; 

     try 
     { 
      command.CommandText = 
       "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"; 
      command.ExecuteNonQuery(); 
      command.CommandText = 
       "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"; 
      command.ExecuteNonQuery(); 

      // Attempt to commit the transaction. 
      transaction.Commit(); 
      Console.WriteLine("Both records are written to database."); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("Commit Exception Type: {0}", ex.GetType()); 
      Console.WriteLine(" Message: {0}", ex.Message); 

      // Attempt to roll back the transaction. 
      try 
      { 
       transaction.Rollback(); 
      } 
      catch (Exception ex2) 
      { 
       // This catch block will handle any errors that may have occurred 
       // on the server that would cause the rollback to fail, such as 
       // a closed connection. 
       Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType()); 
       Console.WriteLine(" Message: {0}", ex2.Message); 
      } 
     } 
    } 
} 

此外,還有注:回滾當一個事務 的try/catch異常處理應始終使用。如果連接終止或者事務已在服務器上回滾,則回滾會生成InvalidOperationException。

但我不能真正相信try/catch是推薦的解決方案來檢查回滾是否可能。

我知道在SQL Server實現中,如果事務是「殭屍」,則SQLTransaction對象在Connection屬性上返回null。

但是,這是相當具體的實現,它只適用於SQL Server。

那麼,是否有一個數據庫獨立的方式來檢測事務是否可以回滾?

TIA 馬丁

回答

1

很多這種複雜性是通過使用在「使用」的聲明一個TransactionScope對象處理 - 檢查出來的MSDN。有一點需要注意的是,一旦TransactionScope被認爲是必要的,TransactionScope會自動「擴大」使用分佈式事務 - 有時這是需要的,而其他時間則不是這樣,因此如果您嵌套TransactionScopes,請小心。

0

問題是,在非SQL 2005中,transactionscope被提升爲分佈式事務,這是相當的開銷。