SQL Transaction Processing)

Source: Internet
Author: User
In many project development scenarios, such as registering a forum user, successful registration is divided into two parts. The first part is to insert a record into the user table first, insert a record to the operation log table. this can be divided into two steps, because the second statement can be executed only after the first insert is successful. in case the first article succeeds, an emergency occurs when the second article is executed, such as a computer crash or a power failure. the system should return the user's status to the status before registration. that is to say, this user registration fails...

To implement the above functions, you need to use SQL transaction processing. The following is a simple example:

Sqlconnection con = new sqlconnection ("Server = (local); database = dB; user id = sa; Pwd = ");
Con. open ();
Sqltransaction ST = con. begintransaction (); // create the Object Transaction named ST through the begintransaction method of sqlconnection
Sqlcommand COM = con. createcommand ();
Com. Transaction = sT; // assign the sqltransaction object to the transaction attribute of the sqlcommand object
Try
{
// Insert registration information to the user table
Com. commandtext = ""; // The insert statement is omitted here. You have to write it yourself ....
Com. executenonquery ();
// Insert data into the log table
Com. commandtext = ""; // The insert statement is also omitted here. You have to write it yourself ....
Com. executenonquery ();
St. Commit (); // submit a transaction
Response. Write ("<SCRIPT> alert ('registration successful! '); Location = 'javascript: history. Go (-1)' </SCRIPT> ");
}
Catch (Exception error)
{
St. rollback (); // rollback
}

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.