asp.net use transactions _ Practical Tips

Source: Internet
Author: User
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 ();
}
}
}
}

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.