What is CommitTrans?
The CommitTrans method of the Connection object is used to save all changes made during a transaction.
-
It is always called after BeginTrans once all database operations are complete and successful.
-
Once committed, the changes become permanent in the database.
Syntax
Connection.CommitTrans
How it Works
-
You call BeginTrans to start a transaction.
-
Execute one or more database commands (INSERT, UPDATE, DELETE).
-
If all commands succeed, call CommitTrans → all changes are permanently written.
-
If any command fails, call RollbackTrans → all changes are undone.
Example: Using CommitTrans
Dim conn
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=MyServer;Initial Catalog=MyDB;User Id=sa;Password=pass;"
On Error GoTo TransactionError
' Start the transaction
conn.BeginTrans
' Execute multiple commands
conn.Execute "UPDATE Accounts SET Balance = Balance - 100 WHERE AccountID = 1"
conn.Execute "UPDATE Accounts SET Balance = Balance + 100 WHERE AccountID = 2"
' Commit the transaction if all commands succeed
conn.CommitTrans
Response.Write "Transaction completed and committed successfully."
ExitHere:
conn.Close
Set conn = Nothing
Exit Sub
TransactionError:
' Rollback transaction if an error occurs
conn.RollbackTrans
Response.Write "Transaction failed. All changes rolled back."
Resume ExitHere
Key Points
-
CommitTrans only works after BeginTrans — calling it without starting a transaction may cause an error.
-
Once committed, changes are permanent — they cannot be rolled back.
-
Always pair with error handling: if something goes wrong, use RollbackTrans.
-
Multiple BeginTrans calls can create nested transactions; CommitTrans commits the current level.
In short: