SqlTransaction 類

表示要在 SQL Server 數據庫中處理的 Transact-SQL 事務。無法繼承此類。 

應用程序通過在 SqlConnection 對象上調用 BeginTransaction 來創建 SqlTransaction 對象。對 SqlTransaction 對象執行與該事務關聯的所有後續操作(例如提交或中止該事務)。  

在提交或回滾 SqlTransaction 時,應始終使用 Try/Catch 進行異常處理。如果連接終止或事務已在服務器上回滾,則 CommitRollback 都會生成 InvalidOperationException。 

 下面的示例創建一個 SqlConnection 和一個 SqlTransaction。此示例還演示如何使用 BeginTransactionCommitRollback 等方法。出現任何錯誤時事務都會回滾。Try/Catch 錯誤處理用於處理嘗試提交或回滾事務時的所有錯誤。

 

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章