当前位置:编程学习 > C#/ASP.NET >>

.net中的事务处理(转自msdn)

答案:Transaction Control
Building Distributed Applications with .NET
Priya Dhawan
Microsoft Developer Network

November 2001

Summary: This article describes how to run local and distributed transactions in your Microsoft .NET applications. (14 printed pages)

Contents
Introduction
Local and Distributed Transactions
   Database Transactions
   Manual Transactions
   Automatic Transactions
Conclusion

Introduction
A transaction is a series of operations performed as a single unit of work. By binding a set of related operations together in a transaction, you ensure the consistency and reliability of the system despite any errors that occur. All operations in a transaction must complete successfully in order to make the transaction successful.

A transaction has a beginning and an end that specify its boundary within which it can span processes and machines. All resources within a transaction boundary participate in the same transaction. To maintain consistency across resources within a transaction boundary, a transaction must exhibit ACID properties, which are Atomicity, Consistency, Isolation, and Durability. See Processing Transactions in them Microsoft .NET Framework SDK and Transaction Processing in the Microsoft Platform SDK for details on transaction processing fundamentals.

In this article, we will show how you can run local and distributed transactions in your Microsoft .NET applications.

Local and Distributed Transactions
A local transaction is one whose scope is a single transaction-aware data resource, such as a Microsoft® SQL Server™ database or MSMQ message queue. For example, a single database system can enforce the ACID rules when it holds all the data involved in a transaction. In the case of SQL Server, there is an internal transaction manager that provides commit and rollback behavior.

Distributed transactions can span heterogeneous transaction-aware data resources and may include a wide range of activities such as retrieving data from a SQL Server database, reading messages from a Message Queue Server, and writing to other databases. Programming of distributed transactions is simplified by software that coordinates commit and abort behavior and recovery across several data resources. Microsoft Distributed Transaction Coordinator (DTC) is one such technology. It implements a two-phase commit protocol that ensures the transaction outcome is consistent across all data resources involved in a transaction. DTC only supports applications that have implemented compatible interfaces for management of transactions. These applications are referred to as Resource Managers (see Distributed Transactions in the .NET Framework Developer's Guide for more information on this topic) and many are currently available, including MSMQ, Microsoft SQL Server, Oracle, Sybase, and others.

Database Transactions
Invoking a stored procedure that wraps required operations within the BEGIN TRANSACTION and COMMIT/ROLLBACK TRANSACTION statements yields the best performance by allowing you to run the transaction in a single round-trip to the database server. Database transactions also support nested transactions, which means you can start a new transaction from within an active transaction.

In the following code snippet, the BEGIN TRANSACTION statement begins a new transaction. You can end a transaction either by committing changes to the database using the COMMIT TRANSACTION statement or by undoing all the changes if any error occurs using the ROLLBACK TRANSACTION statement:

CREATE PROCEDURE Proc1

AS
   -- Begin the transaction
   BEGIN TRANSACTION
   -- Do transaction operations
   …
   -- Check for any Error
   If @@Error <> 0
      -- Rollback the Transaction
      ROLLBACK TRANSACTION
   …
   -- Commit the Transaction
   COMMIT TRANSACTION

The next stored procedure accepts an XML representation of an Order as an input parameter. To make appropriate insertions into the Orders and OrderDetails tables, the stored procedure loads and parses the XML using the sp_xmlpreparedocument system stored procedure. As you see in the code, the stored procedure wraps all the operations in an explicit transaction so that if any of the operations fail to execute all the changes made are rolled back.

Note that the procedure sets XACT_ABORT to ON, which specifies that the SQL server will automatically roll back the transaction in case any of the statements fail to complete.

CREATE PROCEDURE InsertOrder
@Order  NVARCHAR(4000) = NULL
, @OrderId int Output
AS
   SET NOCOUNT ON
   DECLARE @hDoc INT
   DECLARE @PKId  INT
   -- Specify that the SQL Server automatically rolls back the current
   -- transaction if a Transact-SQL statement raises a run-time error.
   SET XACT_ABORT ON
   -- Begin the transaction
   BEGIN TRANSACTION
   -- Load and Parse the incoming XML represeting an Order into an
   -- XMLDocument
   EXEC sp_xml_preparedocument @hDoc OUTPUT, @Order
   -- Select order header from the Order node in the XMLDocument and      
   -- insert it into the Orders table
   INSERT Orders(CustomerId,
                  OrderDate,
                  ShipToName,
                  ShipToAddressId,
                  OrderStatus)
SELECT CustomerId, CONVERT(DateTime,OrderDate), ShipToName,
ShipToAddressId, OrderStatus
   FROM OPENXML(@hDoc, '/NewDataSet/Orders')
   WITH ( CustomerId int 'CustomerId',
          OrderDate nvarchar(23) 'OrderDate',
          ShipToName nvarchar(40) 'ShipToName',
          ShipToAddressId int 'ShipToAddressId',
          OrderStatus  int 'OrderStatus')
   -- Select the OrderId of the Order just inserted into the Orders table
   -- to use it while inserting order details
   SELECT @PKId = @@IDENTITY
   -- Select order details from the Details node in the XMLDocument and      
   -- insert them into the OrderDetails table
   INSERT OrderDetails (OrderId,
                       ItemId,
                       UnitPrice,
                       Quantity)
   SELECT @PKId as OrderId, ItemId, UnitPrice, Quantity
   FROM OPENXML(@hDoc, '/NewDataSet/Details')
   WITH (ItemId int '

上一个:.net中的事务处理(二)
下一个:Windows Forms简介(转)

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,