use strict;
use warnings;
use DBI;
#1
my $dbh = DBI->connect ("dbi:SQLite:Test.sqlite");
die "connect failed: $DBI::errstr" if ! $dbh;
#2
local $dbh->{AutoCommit} = 0; # Use transacted processing
local $dbh->{RaiseError} = 1; # die on processing errors
local $dbh->{PrintError} = 0; # Suppress printing errors
#3
my $sql =
qq{CREATE TABLE People (name VARCHAR(128), age INTEGER)};
#4
eval {
$dbh->do ($sql);
$dbh->commit ();
};
#5
if ($@) {
# An error occurred
$dbh->rollback ();
die $@;
}
####
local $dbh->{RaiseError} = 1;
local $dbh->{PrintError} = 0;
eval {
$dbh->begin_work;
... queries go here ...
$dbh->commit;
1;
} or do {
my $err = $@ || "Unknown error";
eval {
$dbh->rollback;
1;
} or do {
$err .= "[ROLLBACK FAILED: " . ($@ || "Unknown reasons") . "]";
}
die $err;
}
##
##
use strict;
use warnings;
use DBI;
my $dbh = DBI->connect ("dbi:SQLite:Test.sqlite");
die "connect failed: $DBI::errstr" if ! $dbh;
$dbh->{AutoCommit} = 0; # Use transacted processing
$dbh->{RaiseError} = 1; # die on processing errors
my %people = (
Fred => 23,
Jane => 22,
Boyd => 27,
Tania => 28,
Julie => 27,
Kyle => 21,
);
#1
my $sql = qq{INSERT INTO People (name, age) VALUES (?, ?)};
my $entries = 0;
eval {
my $sth = $dbh->prepare ($sql); #2
while (my ($name, $age) = each %people) { #3
++$entries if $sth->execute ($name, $age); #4
}
$dbh->commit (); #5
return 1;
} or do {
my $err = $@ || "Unknown error inserting data";
eval {$dbh->rollback ()} or $err .= "\n Rollback processing failed!";
die $err;
};
print "Added $entries rows to the People table\n";
##
##
$entries = $sth->execute_array ({}, [keys %people], [values %people]);
##
##
#1
my $sql = qq{SELECT name, age FROM People WHERE name LIKE ? AND age < ?};
eval {
#2
my $sth = $dbh->prepare ($sql);
$sth->execute ('%e', 25); #3
#4
while (my $row = $sth->fetchrow_hashref ()) {
printf "%-10s %3d\n", @{$row}{'name', 'age'};
}
};