代码
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");
}
}
//提交
protected void Button1_Click(object sender, EventArgs e)
{
string str1 = this.TextBox1.Text;
string str2 = this.TextBox2.Text;
using (GetConnection())
{
conn.Open();
//事务
SqlTransaction tran;
tran = conn.BeginTransaction();
//提交一
SqlCommand cmd1 = new SqlCommand("insert into m1(m1,m2)values('" + str1 + "','" + str2 + "')", conn);
cmd1.Transaction = tran;
//提交二
SqlCommand cmd2 = new SqlCommand("insert into messages(msg)values('" + str1 + "')", conn);
cmd2.Transaction = tran;
try
{
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
tran.Commit();//提交事物
Response.Write("<script>alert('全部提交OK')</script>");
}
catch
{
tran.Rollback();//回滚操作
Response.Write("<script>alert('事务回滚')</script>");
}
finally
{
conn.Close();
}
}
}
}