asp.net 使用事务
程序员文章站
2024-03-08 22:02:28
asp.net操作事务非常的简单,代码如下: 代码 复制代码 代码如下: using system; using system.collections.generic; u...
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();
}
}
}
}