重載
BeginTransaction() | 開始數據庫事務。 |
BeginTransaction(IsolationLevel) | 以指定的隔離級別啟動數據庫事務。 |
BeginTransaction(String) | 以指定的事務名稱啟動數據庫事務。 |
BeginTransaction(IsolationLevel, String) | 以指定的隔離級別和事務名稱啟動數據庫事務。 |
BeginTransaction()
開始數據庫事務。
public System.Data.SqlClient.SqlTransaction BeginTransaction ();
返回
表示新事務的對象。
例外
使用多個活動結果集 (MARS) 時,不允許並行事務。
不支持並行事務。
示例
下面的示例創建一個 SqlConnection 和一個 SqlTransaction 。 它還演示了如何使用 BeginTransaction 、、 Commit 和 Rollback 方法。
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); } } } }
注解
此命令映射到 BEGIN TRANSACTION 的 SQL Server 實現。
必須使用或方法顯式提交或回滾事務 Commit Rollback 。 為了確保 SQL Server 事務管理模型的 .NET Framework 數據提供程序正確執行,請避免使用其他事務管理模型,如 SQL Server 提供的模型。
備注
如果未指定隔離級別,則使用默認的隔離級別。 若要使用方法指定隔離級別 BeginTransaction ,請使用 iso
) (采用參數的重載 BeginTransaction 。 在事務完成后,為事務設置的隔離級別將保留,直到關閉或釋放連接。 在未啟用快照隔離級別的數據庫中,將隔離級別設置為 snapshot 不會引發異常。 該事務將使用默認隔離級別完成。
注意
如果事務已啟動並且服務器上發生級別16或更高的錯誤,則在調用方法之前,不會回滾事務 Read 。 ExecuteReader上不引發異常。
注意
如果查詢返回大量的數據和調用 BeginTransaction
, SqlException 則會引發,因為 SQL Server 在使用 MARS 時不允許並行事務。 若要避免此問題,請始終在打開任何讀取器之前將事務與命令和/或連接關聯。