Asp. NET operations transaction is very simple, the code is as follows:
Code
Copy Code code 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 Button1_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 A
SqlCommand cmd1 = new SqlCommand ("INSERT into M1 (M1,M2) VALUES (' + str1 +" ', ' "+ str2 +") ", conn);
Cmd1. Transaction = Tran;
Submit Two
SqlCommand cmd2 = new SqlCommand ("INSERT into messages (msg) VALUES (' + str1 + ')", conn);
Cmd2. Transaction = Tran;
Try
{
Cmd1. ExecuteNonQuery ();
Cmd2. ExecuteNonQuery ();
Tran.commit ()/Submit sth.
Response.Write (<script>alert (' All submitted ok ') </script> ");
}
Catch
{
Tran. Rollback ();/rollback operation
Response.Write ("<script>alert (' transaction rollback ') </script>");
}
Finally
{
Conn. Close ();
}
}
}
}