Using Transactions
Description
Many databases allow you to perform record updates within the context of a transaction. A transaction is useful when you want to make multiple updates or no updates at all. You bracket the INSERT, DELETE, or UPDATE commands with the SQL::Connection BeginTransaction(?) and CommitTransaction(?) methods. In the case when you cannot complete all the required updates, you conclude with the RollBackTransaction(?) method instead of the CommitTransaction() method. Suppose you want to copy records from the Product table to the New_Product table. Then, after you have confirmed the copy, you want delete these records from the Product table.
First, create and define variables. The select_cmd will select the records to copy. The delete_cmd will select the records to delete.
dim conn as sql::connection dim select_cmd as C dim delete_cmd as C select_cmd = "select * from ProductA" delete_cmd = "delete * from ProductA"
Establish the connection. If there is an error, display a message, and end the script.
if .not. conn.open("{A5API=Access,FileName='C:\Program Files\A5V8\MDBFiles\Alphasports.mdb',UserName='Admin'}") then ui_msg_box("Error", "Could not establish connection" + crlf()+ conn.CallResult.text) end end if
Select the data to copy. If there is an error, display a message, and end the script.
if .not. conn.execute(select_cmd) then ui_msg_box("Error", "Could not execute query" + crlf()+ conn.CallResult.text) conn.close() end end if
If the records were established, it is time to begin the transaction with the BeginTransaction(?) method.
conn.BeginTransaction()
Copy records from ProductA to ProductB. If there is an error, roll back the transaction with the RollBackTransaction(?) method, display a message, and end the script.
if .not. conn.InsertData("", "ProductB", conn.ResultSet) ui_msg_box("Error", "Could not insert data into ProductB") conn.RollBackTransaction() conn.close() end end if
Delete the records in ProductA. If there is an error, roll back the transaction, display a message, and end the script.
if .not. conn.execute(delete_cmd) ui_msg_box("Error", "Could not delete data from ProductA" + crlf()+ conn.CallResult.text) conn.RollBackTransaction() conn.close() end end if
Finally, commit the transaction and close the connection.
conn.CommitTransaction() conn.close()
Limitations
Desktop applications only. Not available in Community Edition.
See Also