实用技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > ASP.NET > 实用技巧 > asp.net 事务

asp.net 使用事务

作者:

假如我们要同时更新几张表就必定需要使用事务操作。
ASP.NET操作事务非常的简单,代码如下:
代码
复制代码 代码如下:

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();
}
}
}
}
您可能感兴趣的文章:
阅读全文