Transaction Processing | transaction processing
<%
' ASP transaction processing.
' Test database is SQL Server, server is native, database name is test, table name is a, two field ID (int) primary key ID, 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
' The above code establishes the database connection
Conn. BeginTrans ' Affairs started
strsql1= "Update a set num=1000 where id=24" ' first SQL statement is update. (grammatically correct)
strsql2= INSERT into a (num) values (' a ') ' The second SQL statement is an incorrect SQL statement
strsql3= INSERT into a (num) VALUES (33333) "' The third SQL statement is the correct SQL statement
Call Conn.execute (STRSQL1)
Call Conn.execute (STRSQL2)
Call Conn.execute (STRSQL3)
If Conn. Errors.count=0 Then
Conn.committrans ' If no conn error, execute transaction commit
Else
Conn. RollbackTrans ' or roll back
End If
%>
The above code after debugging, can be normal for transaction processing. But sometimes, we don't want to display compilation errors to the user.
Then we need to be in Conn. BeginTrans followed by On Error Resume Next
But because of the use of On Error Resume Next. Conn. Errors.Count can only get the result of the Conn return of the last database operation. The three SQL statements above, because the last SQL statement is correct, the transaction is invalid. Then we need to make a corresponding change to the error handling.
If Conn. Errors.count=0 then should be changed to if Err.number=0 then
In this way, we can do other actions or hints when the database rolls back. The modified code is as follows:
<%
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
' The above code establishes the database connection
Conn. BeginTrans ' Affairs started
On Error Resume Next ' added code
strsql1= "Update a set num=1000 where id=24" ' first SQL statement is update. (grammatically correct)
strsql2= INSERT into a (num) values (' a ') ' The second SQL statement is an incorrect SQL statement
strsql3= INSERT into a (num) VALUES (33333) "' The third SQL statement is the correct SQL statement
Call Conn.execute (STRSQL1)
Call Conn.execute (STRSQL2)
Call Conn.execute (STRSQL3)
If Err.Number =0 Then
Conn.committrans ' If no conn error, execute transaction commit
Else
Conn. RollbackTrans ' or roll back
' Other actions after rolling back
Strerr=err. Description
Response.Write "Database Error! Error log: <font color=red> "&strerr &" </font> "
Response.End
End If
%>