Transaction Processing in ASP. NET

Source: Internet
Author: User

In ADO. net, you can use the connection and transaction objects to control transactions. To execute a transaction, perform the following operations:

Call the begintransaction method of the connection object to mark the start of the transaction. Begintransaction returns a reference to transaction. Keep this reference so that it is assigned to the command registered in the transaction.

Assign the transaction object to the transaction attribute of the command to be executed. If you execute command on the connection through the active transaction object, but the transaction object has not been assigned the transaction attribute to the command, an exception is thrown.

Run the required command.

Call the commit method of the transaction object to complete the transaction, or call the rollback method to cancel the transaction.

BelowCodeMicrosoft? SQL Server? To demonstrate the transaction logic.

Sqlconnection myconnection = new sqlconnection ("Data Source = localhost; initial catalog = northwind; Integrated Security = sspi ;");
Myconnection. open ();
// Start a transaction
Sqltransaction mytrans = myconnection. begintransaction ();

// create a command for the transaction
sqlcommand mycommand = new sqlcommand ();
mycommand. connection = myconnection;
mycommand. transaction = mytrans;
try
{< br> mycommand. commandtext = "insert into region (regionid, regiondescription) values (100," Description ")";
mycommand. executenonquery ();
mycommand. commandtext = "insert into region (regionid, regiondescription) values (101," Description ")";
mycommand. executenonquery ();
mytrans. commit ();
console. writeline ("both records are written to database. ");
}< br> catch (exception e)
{< br> mytrans. rollback ();
console. writeline (E. tostring ();
console. writeline ("neither record was written to database. ");
}< br> finally
{< br> myconnection. close ();
}< br>

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.