Database Reference
In-Depth Information
back the transaction. The following code illustrates this. It uses exceptions to detect
transaction failure, so it assumes that exceptions are enabled for PDO errors:
try
{
$dbh -> beginTransaction ();
$dbh -> exec ( "UPDATE money SET amt = amt - 6 WHERE name = 'Eve'" );
$dbh -> exec ( "UPDATE money SET amt = amt + 6 WHERE name = 'Ida'" );
$dbh -> commit ();
}
catch ( Exception $e )
{
print ( "Transaction failed, rolling back. Error was: \n " );
print ( $e -> getMessage () . " \n " );
# empty exception handler in case rollback fails
try
{
$dbh -> rollback ();
}
catch ( Exception $e2 ) { }
}
17.7. Using Transactions in Python Programs
Problem
You want to perform a transaction in a DB API script.
Solution
Use the standard DB API transaction support mechanism.
Discussion
The Python DB API abstraction provides transaction processing control through con‐
nection object methods. The DB API specification indicates that database connections
should begin with auto-commit mode disabled. Therefore, when you open a connection
to the database server, Connector/Python disables auto-commit mode, which implicitly
begins a transaction. End each transaction with either commit() or rollback() . The
commit() call occurs within a try statement, and the rollback() occurs within the
except clause to cancel the transaction if an error occurs:
try :
cursor = conn . cursor ()
# move some money from one person to the other
cursor . execute ( "UPDATE money SET amt = amt - 6 WHERE name = 'Eve'" )
cursor . execute ( "UPDATE money SET amt = amt + 6 WHERE name = 'Ida'" )
cursor . close ()
conn . commit ()
Search WWH ::




Custom Search