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 ();
}
}
}
}