新客网WWW.XKER.COM:致力做中国最专业的网络学院!
学院: 操作系统 - 网络应用 - 服务器 - 网络安全 - 工具软件 - 办公软件 - Web开发 - 数据库 - 网页设计 - 图形图像 - 媒体动画 - 硬件学堂 - 存储频道 - QQ专区
您的位置:首页 > 软件开发 > Web开发 > Asp教程 > 正文:asp事务处理的另外一个方法

asp事务处理的另外一个方法

新客网 XKER.COM 2005-07-12 来源: 收藏本文
 

<%
'asp事务处理。
'测试数据库为sql server,服务器为本机,数据库名为test,表名为a,两个字段id(int)主键标识,num(int)
set conn=server.CreateObject("adodb.connection")
strConn="provider=sqloledb.1;persist security info=false;uid=sa;pwd=sa;Initial Catalog=test;Data Source=."
conn.Open strConn
'以上代码建立数据库连接
conn.BeginTrans '事务开始
strSql1="update a set num=1000 where id=24" '第一个sql语句为update。(语法正确)
strSql2="insert into a(num) values('a')" '第二个sql语句为错误的sql语句
strSql3="insert into a(num) values(33333)" '第三个sql语句为正确的sql语句


call conn.execute(strSql1)  
call conn.execute(strSql2)  
call conn.execute(strSql3)  


if conn.Errors.Count=0 then  
      conn.CommitTrans  '如果没有conn错误,则执行事务提交
else
      conn.RollbackTrans '否则回滚
end if
%>
以上代码经调试,可以正常的进行事务处理。但是有时候,我们并不想将编译错误显示给用户。
则我们需要在conn.BeginTrans后面加上On error resume next
但是因为用到了On error resume next。conn.Errors.Count只能获得最后一个数据库操作的conn返回的结果 。上面的三个sql语句,因为最后一个sql语句是正确的,则此事务处理就无效了。那我们需要对出错处理作出相对应的修改。
if conn.Errors.Count=0 then应该改为if err.number=0 then
这样,我们可以在数据库回滚后同时做出其他相对应的操作或者提示。修改后的代码如下:
<%
set conn=server.CreateObject("adodb.connection")
strConn="provider=sqloledb.1;persist security info=false;uid=sa;pwd=sa;Initial Catalog=test;Data Source=."
conn.Open strConn
'以上代码建立数据库连接
conn.BeginTrans '事务开始
on error resume next '增加的代码
strSql1="update a set num=1000 where id=24" '第一个sql语句为update。(语法正确)
strSql2="insert into a(num) values('a')" '第二个sql语句为错误的sql语句
strSql3="insert into a(num) values(33333)" '第三个sql语句为正确的sql语句


call conn.execute(strSql1)  
call conn.execute(strSql2)  
call conn.execute(strSql3)  


if err.number =0 then  
    conn.CommitTrans  '如果没有conn错误,则执行事务提交
else
    conn.RollbackTrans '否则回滚
    '回滚后的其他操作
    strerr=err.Description
    Response.Write "数据库错误!错误日志:<font color=red>"&strerr &"</font>"
    Response.End
end if


%>

收藏】 【评论】 【推荐】 【投稿】 【打印】 【关闭
发表评论
要记得去论坛讨论,点击注册新会员匿名评论
评论内容:不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
阅读排行
随机推荐
实用信息推荐