Asp.net and asp.net

Source: Internet
Author: User
Tags asp net msmq

Asp.net and asp.net

Transaction processing is a common problem during data processing. The following three methods are commonly used:
Method 1: directly write data to SQL
Use begin trans, commit trans, and rollback trans in the Stored Procedure
Begin trans
Declare @ orderDetailsError int, @ procuntError int
Delete from [order details] where productid = 42
Select @ orderDetailsError = @ error
Delete from products where productid = 42
Select @ procuntError = @ error
If (@ orderDetailsError = 0 and @ procuntError = 0)
COMMIT TRANS
Else
ROLLBACK TRANS
Advantages:
All transaction logic is included in a separate call
Has the best performance to run a transaction
Independent from applications
Restrictions:
The transaction context only exists in database calls.
Database code is related to the Database System
Method 2: using ADO. Net
The advantage of using ADO. Net is that you can manage transactions in the middle layer. Of course, you can also choose to implement it at the data layer.
The SqlConnection and OleDbConnection objects have a BeginTransaction method, which can return SqlTransaction
Or OleDbTransaction object. In addition, this object has the Commit and Rollback methods to manage transactions.
SqlConnection sqlConnection = new SqlConnection ("workstation id = WEIXIAOPING; packet size = 4096; user id = sa; initial catalog = Northwind; persist security info = False ");
SqlConnection. Open ();
SqlTransaction myTrans = sqlConnection. BeginTransaction ();
SqlCommand sqlInsertCommand = new SqlCommand ();
SqlInsertCommand. Connection = sqlConnection
SqlInsertCommand. Transaction = myTrans;
Try {
SqlInsertCommand. CommandText = "insert into tbTree (Context, ParentID) values ('beijing', 1 )";
SqlInsertCommand. ExecuteNonQuery ();
SqlInsertCommand. CommandText = "insert into tbTree (Context, ParentID) values ('shanghai', 1 )";
SqlInsertCommand. ExecuteNonQuery ();
MyTrans. Commit ();
} Catch (Exception ex)
{
MyTrans. Rollback ();
}
Finally
{
SqlConnection. Close ();
}
Advantages:
Simplicity
Almost as fast as data transactions
The proprietary code of different databases is hidden.
Disadvantages:
Transactions cannot be connected across multiple databases
Transactions are executed on the database connection layer. Therefore, you need to maintain a database connection during the transaction process.
ADO. net distributed transactions can also span multiple databases. However, if one of the SQL server databases is used, the SQL SERVER is used to connect to the SERVER to connect to another database, but it is not allowed between DB2 and Orcal.
The preceding two transactions are commonly used transaction processing methods.
Method 3 COM + transaction (Distributed Transaction)
. Net Framework relies on MTS/COM + to support Automatic transactions. COM + uses Microsoft Distributed Transaction Coordinator (DTC) as the Transaction Manager and Transaction Coordinator to run transactions in a Distributed environment.
In this way.. Net application programs run across multiple resources combined with different operations (for example, insert orders into the SQL Server database, write messages to the Microsoft Message Queue (MSMQ) queue, and retrieve data from the Oracle database)
.
The COM + transaction processing class must inherit System. EnterpriseServices. ServicedComponent. In fact, web service inherits System. EnterpriseServices. ServicedComponent, so web service also supports
COM + transaction.
Define a class for COM + Transaction Processing
[Transaction (TransactionOption. Required)]
Public class DataAccess: System. EnterpriseServices. ServicedComponent
{

}
The TransactionOption Enumeration type supports five COM + values (Disabled, NotSupported, Required, RequiresNew, Supported)
Disabled ignores any transactions in the current context.
NotSupported uses uncontrolled transactions to create components in the context.
Required shares the transaction if the transaction exists, and creates a new transaction if necessary.
RequiresNew creates a component using a new transaction, regardless of the status of the current context.
Supported shares the transaction if the transaction exists.
In general, components in COM + need Required or Supported. RequiresNew is useful when a component is used for recording or checking the account, because the component should be isolated from the commit or rollback of other transactions in the activity.
A derived class can overload any attribute of a base class. For example, if you select Required for DataAccess, the derived class can still be reloaded and specify RequiresNew or another value.

COM + transactions are manually processed and automatically processed. Automatic processing is to add [AutoComplete] before the method to be automatically processed. It is determined to submit or roll back based on the normal method or thrown exception of the method.
Manual processing is to call the EnableCommit, SetComplete, and SetAbort methods in the ContextUtil class.
Public string testTransaction ()
{
Try
{
ContextUtil. EnableCommit ();
InsertARecord1 ();
InsertARecord2 ();
ContextUtil. SetComplete ();
Return "succeed! ";
}
Catch (Exception ex)
{
ContextUtil. SetAbort ();
Return "failed! ";
}

}
Public void InsertARecord1 ()
{

String strconn = "workstation id = WEIXIAOPING; packet size = 4096; user id = sa; initial catalog = Northwind; persist security info = False ";
SqlConnection conn = new SqlConnection (strconn );
Conn. Open ();
SqlCommand command = new SqlCommand ("insert into tbTree (Context, ParentID) values ('beijing', 1)", conn );
Command. ExecuteNonQuery ();
Conn. Close ();

}
Public void InsertARecord2 ()
{

String strconn = "workstation id = WEIXIAOPING; packet size = 4096; user id = sa; initial catalog = Northwind; persist security info = False ";
SqlConnection conn = new SqlConnection (strconn );
Conn. Open ();
SqlCommand command = new SqlCommand ("insert into tbTree (Context, ParentID) values ('shanghai', 1)", conn );
Command. ExecuteNonQuery ();
Conn. Close ();
}
In systems that require transactions to run across MSMQ and other resources that can identify transactions (such as SQL Server databases), you can only use DTC or COM + transactions, but there is no other choice. DTC coordinates all resource managers involved in distributed transactions,
It also manages transaction-related operations.
The disadvantage of this approach is that the performance is reduced due to the overhead of DTC and COM interoperability.
The class for processing COM + transactions must be named strongly.

Reference from:


Asp net database transaction processing code, for example, update

Here is a simple example:

Begin tran // start the transaction
Declare @ error int // declare a variable for receiving errors
Set @ error = 0 // assign a value to the parameter
Exec (@ str2) // execute the statement
Set @ error = @ error + @ error // if an error occurs, assign the error message to the variable.
Exec (@ str) // execute the next statement
Set @ error = @ error + @ error // if an error occurs, assign the error message to the variable.

If (@ error <> 0) // determines whether the variable is an initial value. if not, an error occurs during execution.
Begin
Rollback tran // roll back the transaction
End
Else // If the variable is the initial value, the execution is successful.
Begin
Commit tran // submit the transaction
End // execution completed

Implementation of oracle transaction processing in aspnet

You can use the items that come with oracle. Write two insert statements in a cmd and add the begin and commit commands, which are separated by commas. The specific idea is as follows:
StringBuilder oracleSql = new StringBuilder ("Begin ");
OracleSql. Append (insertsql1)
OracleSql. Append (";")
OracleSql. Append (insertsql2)
OracleSql. Append (";")
OracleSql. Append ("commit; end ;");
You should know how to write it later.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.