<% ‘a(chǎn)sp事務(wù)處理。 ‘測試數(shù)據(jù)庫為sql server,服務(wù)器為本機(jī),數(shù)據(jù)庫名為test,表名為a,兩個(gè)字段id(int)主鍵標(biāo)識(shí),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 ‘以上代碼建立數(shù)據(jù)庫連接 conn.BeginTrans ‘事務(wù)開始 strSql1="update a set num=1000 where id=24" ‘第一個(gè)sql語句為update。(語法正確) strSql2="insert into a(num) values(‘a(chǎn)‘)" ‘第二個(gè)sql語句為錯(cuò)誤的sql語句 strSql3="insert into a(num) values(33333)" ‘第三個(gè)sql語句為正確的sql語句
call conn.execute(strSql1) call conn.execute(strSql2) call conn.execute(strSql3)
if conn.Errors.Count=0 then conn.CommitTrans ‘如果沒有conn錯(cuò)誤,則執(zhí)行事務(wù)提交 else conn.RollbackTrans ‘否則回滾 end if %> 以上代碼經(jīng)調(diào)試,可以正常的進(jìn)行事務(wù)處理。但是有時(shí)候,我們并不想將編譯錯(cuò)誤顯示給用戶。 則我們需要在conn.BeginTrans后面加上On error resume next 但是因?yàn)橛玫搅薕n error resume next。conn.Errors.Count只能獲得最后一個(gè)數(shù)據(jù)庫操作的conn返回的結(jié)果 。上面的三個(gè)sql語句,因?yàn)樽詈笠粋€(gè)sql語句是正確的,則此事務(wù)處理就無效了。那我們需要對出錯(cuò)處理作出相對應(yīng)的修改。 if conn.Errors.Count=0 then應(yīng)該改為if err.number=0 then 這樣,我們可以在數(shù)據(jù)庫回滾后同時(shí)做出其他相對應(yīng)的操作或者提示。修改后的代碼如下: <% 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 ‘以上代碼建立數(shù)據(jù)庫連接 conn.BeginTrans ‘事務(wù)開始 on error resume next ‘增加的代碼 strSql1="update a set num=1000 where id=24" ‘第一個(gè)sql語句為update。(語法正確) strSql2="insert into a(num) values(‘a(chǎn)‘)" ‘第二個(gè)sql語句為錯(cuò)誤的sql語句 strSql3="insert into a(num) values(33333)" ‘第三個(gè)sql語句為正確的sql語句
call conn.execute(strSql1) call conn.execute(strSql2) call conn.execute(strSql3)
if err.number =0 then conn.CommitTrans ‘如果沒有conn錯(cuò)誤,則執(zhí)行事務(wù)提交 else conn.RollbackTrans ‘否則回滾 ‘回滾后的其他操作 strerr=err.Description Response.Write "數(shù)據(jù)庫錯(cuò)誤!錯(cuò)誤日志:<font color=red>"&strerr &"</font>" Response.End end if
%>
|