ASP Transactions _ Application Skills

Source: Internet
Author: User
In programming, you often need to use transactions. A business is a series of operations that must be successful, and all other steps must be undone as long as one operation fails. For example, using ASP to develop a network hard disk system, the user registration part of the things to do are:
1, the user information into the database
2, open a folder for users to store
3. Initialize User action Log

These three steps must use transactions, or in the event of a disk operation failure, but did not undo the database operation, it will cause only landing and can not operate the "dead user" phenomenon.

Because of the special development History of database system, small to access, large to DB2, all with transaction support. The above steps can therefore be expressed as follows:

The following is a reference fragment:
On Error Resume Next
First step:
To record user information into a database in a transactional environment
If ERR Then
Close connection
Exit
Else
Step Two: Create a folder
If ERR Then
Roll back the first step database operation, exit
Else
Step three: Manipulate the log database in a transactional environment
If ERR Then
Roll back the first step and delete the folder created in the second step
Exit
End If
End If
End If
Commit transactions for the first step of the database operation
Commit transactions to the second step of the database operation
End

Each step needs to be judged, if it fails, you need to manually rollback the previous multi-step operation, so that the program becomes complex and difficult to understand. If you update your program in the future and add additional steps, you will need to nest more layers of If ... Else ... End If, making the program process more complex.

The correct solution is to use the ASP's transaction control capabilities. By contacting the MTS Service, IIS can control multiple systems that support transactions, and when the program issues a "failed" signal, all supporting transactions are automatically rolled back, even if the operation is formally completed, and a convenient manual rollback is provided for operations that do not support transactions. The example above is rewritten using the ASP transaction control function as follows:
Copy Code code as follows:

<%@ TRANSACTION = Required%>
On Error Resume Next

Set conn=server.createobject ("ADODB. Connection ")
Conn.Open .....
Conn.execute "INSERT ...."
Conn.close
Set conn=nothing

Set conn2=server.createobject ("ADODB. Connection ")
Conn2.open .....
Conn2.execute "INSERT ...."
Conn2.close
Set conn2=nothing

Set fso=server.createobject ("Scripting.FileSystemObject")
Fso. CreateFolder "..."

If ERR Then
ObjectContext.SetAbort ' notifies all supporting transaction components to roll back and runs manual rollback code
Else
ObjectContext.SetComplete
End If
Set fso=nothing

Sub OnTransactionAbort
Response.Write "Error"
Fso. DeleteFile Server.MapPath ("a.txt") ' FSO manual rollback--delete folder
End Sub
Sub OnTransactionCommit
Response.Write "Complete the mission successfully."
End Sub
%>

The first line of <%@ TRANSACTION = Required%> indicates that this page of ASP files requires MTS transaction support. Each of the operations in the middle is written in a normal order, regardless of the rollback issue. At the end of the program to determine whether there are errors. If there is, call the ObjectContext SetAbort method, IIS notifies all supporting transaction components to rollback (primarily the database) through the MTS service, and runs sub OnTransactionAbort to manually rollback the operations that do not support transactions If no error occurs, the ObjectContext SetComplete method is invoked, and sub OnTransactionCommit is run to display the successful message.

The entire ASP program does not need to judge errors and rollback operations to write redundant code, only to be judged at the end, even if the future increase in multi-step operations, but only in the Sub OnTransactionAbort control can be very convenient, programmers can focus on process writing rather than writing error-correcting code.

In fact, ASP also provides a number of more useful features, waiting for us to use, do not think that ASP use scripting language, the function is necessarily weak.

The following is a reference fragment:
<%
' 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:
The following is a reference fragment:
<%
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
%>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.