在web开发中的三个层次使用事务
2024-07-21 02:15:50
供稿:网友
很多数据库操作需要进行事务,asp.net下面进行事务大致有3个层次:
(1)存储过程层次的事务
(2)ado.net层次的事务
(3)asp.net页面层次的事务
下面分别举例:
首先建立trantest表,字段id(int),test(char)
为id设置主键(利用主键是不允许重复的特性进行事务测试)
假设数据库内存在记录id=1,test='test'
(1)
create procedure tran1
as
begin tran
set xact_abort on
insert into trantest (id,test)values(1,'test')
insert into trantest (id,test)values(2,'test')
commit tran
go
set xact_abort on 表示遇到错误立即回滚
当然你也可以这么写
create procedure tran1
as
begin tran
insert into trantest(id,test)values(1,'test')
if(@@error<>0)
rollback tran
else
begin
insert into trantest(id,test)values(2,'test')
if(@@error<>0)
rollback tran
else
commit tran
end
go
(2)
sqlconnection conn=new sqlconnection(system.configuration.configurationsettings.appsettings["conn"]);
sqlcommand cmd1=new sqlcommand("insert into trantest (id,test)values(1,'test')",conn);
sqlcommand cmd2=new sqlcommand("insert into trantest (id,test)values(1,'test')",conn);
conn.open();
sqltransaction tran=conn.begintransaction();
cmd1.transaction=tran;
cmd2.transaction=tran;
try
{
cmd1.executenonquery();
cmd2.executenonquery();
tran.commit();
}
catch(sqlexception except)
{
tran.rollback();
response.write(except.message);
}
finally
{
conn.close();
}
(3)
添加引用system.enterpriseservices.dll
using system.enterpriseservices;
随便建立一个按钮,在按钮中进行如下操作:
try
{
work1();
work2();
contextutil.setcomplete();
}
catch(system.exception except)
{
contextutil.setabort();
response.write(except.message);
}
然后在页面中添加2个操作,模拟一下在逻辑层调用不同类中的操作的情况
private void work1()
{
sqlconnection conn=new sqlconnection(system.configuration.configurationsettings.appsettings["conn"]);
sqlcommand cmd1=new sqlcommand("insert into trantest (id,test)values(1,'test')",conn);
conn.open();
cmd1.executenonquery();
conn.close();
}
private void work2()
{
sqlconnection conn=new sqlconnection(system.configuration.configurationsettings.appsettings["conn"]);
sqlcommand cmd2=new sqlcommand("insert into trantest (id,test)values(2,'test')",conn);
conn.open();
cmd2.executenonquery();
conn.close();
}
修改前台页面在<%page后面添加 transaction="required" 即可注册会员,创建你的web开发资料库,