Asp.net use transactions

Source: Internet
Author: User

The ASP. NET Operation transaction is very simple and the code is as follows:
Code
Copy codeThe Code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Data;
Using System. Data. SqlClient;
Using System. Transactions;
Public partial class swstudy: System. Web. UI. Page
{
Private SqlConnection conn;
Protected void Page_Load (object sender, EventArgs e)
{
}
Private SqlConnection GetConnection ()
{
If (conn! = Null & conn. State = ConnectionState. Open)
{
Return conn;
}
Else
{
Return conn = new SqlConnection ("server = PC-200911131211; database = test; uid = sa; pwd = sa123456 ");
}
}
// Submit
Protected void button#click (object sender, EventArgs e)
{
String str1 = this. TextBox1.Text;
String str2 = this. TextBox2.Text;
Using (GetConnection ())
{
Conn. Open ();
// Transaction
SqlTransaction tran;
Tran = conn. BeginTransaction ();
// Submit 1
SqlCommand cmd1 = new SqlCommand ("insert into m1 (m1, m2) values ('" + str1 + "', '" + str2 + "')", conn );
Statement 1.transaction = tran;
// Submit 2
SqlCommand cmd2 = new SqlCommand ("insert into messages (msg) values ('" + str1 + "')", conn );
Export 2.transaction = tran;
Try
{
Statement 1.executenonquery ();
Listen 2.executenonquery ();
Tran. Commit (); // submit a transaction
Response. Write ("<script> alert ('submit all OK ') </script> ");
}
Catch
{
Tran. Rollback (); // Rollback operation
Response. Write ("<script> alert ('transaction rollback') </script> ");
}
Finally
{
Conn. Close ();
}
}
}
}

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.