Using Transactions in Perl Programs
Problem
You want to perform a transaction in a Perl DBI script.
Solution
Use the standard DBI transaction support mechanism.
Discussion
The Perl DBI transaction mechanism is based on explicit manipulation of auto-commit mode:
Turn on the
RaiseError
attribute if it’s not enabled and disablePrintError
if it’s on. You want errors to raise exceptions without printing anything, and leavingPrintError
enabled can interfere with failure detection in some cases.Disable the
AutoCommit
attribute so that a commit will be done only when you say so.Execute the statements that make up the transaction within an
eval
block so that errors raise an exception and terminate the block. The last thing in the block should be a call tocommit()
, which commits the transaction if all its statements completed successfully.After the
eval
executes, check the$@
variable. If$@
contains the empty string, the transaction succeeded. Otherwise, theeval
will have failed due to the occurrence of some error and$@
will contain an error message. Invokerollback()
to cancel the transaction. If you want to display an error message, print$@
before callingrollback()
.
The following code shows how to follow those steps to perform our sample transaction:
# set error-handling and auto-commit attributes correctly $dbh->{RaiseError} = 1; # raise exception if an error occurs $dbh->{PrintError} = 0; # don't print an error message $dbh->{AutoCommit} = 0; # disable auto-commit eval { # move some ...
Get MySQL Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.