Saturday, July 9, 2011

How to Manage MySQL Transactions and AutoCommit in Perl DBI

When working with databases in Perl using DBI, you often want to group multiple operations into a single transaction. You can do this by using $dbh->begin_work (which temporarily turns off AutoCommit) and then calling $dbh->commit when you are done.

# 1. Connect to the database
my $dbh = DBI->connect("DBI:mysql:database_name", "username", "password");

# 2. Prepare your SQL statement or stored procedure
my $sth = $dbh->prepare("call sp_get_workitems (1,1)");

# 3. Start the transaction 
# (This is equivalent to setting $dbh->{'AutoCommit'} = 0;)
$dbh->begin_work or die $dbh->errstr;      

# 4. Execute the query and fetch results
$sth->execute();
my ($result) = $sth->fetchrow_array();

# 5. Commit the transaction to save changes
$dbh->commit;

No comments: