富贵资源网 Design By www.hznty.com
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();
}
}
}
}
代码
复制代码 代码如下:
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();
}
}
}
}
富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com
暂无评论...