Outline Usage
To use DBI, first you need to load the DBI module:
use DBI; use strict;
(The use strict;
isn’t
required but is strongly recommended.)
Then you need to connect to your data source and get a handle for the connection:
$dbh = DBI->connect($dsn, $user, $password, { RaiseError => 1, AutoCommit => 0 });
Since connecting can be expensive, you generally just connect at the start of your program and disconnect at the end.
Explicitly defining the required
AutoCommit
behavior is strongly
recommended and may become mandatory in a later version. This
determines if changes are automatically committed to the database
when executed, or if they need to be explicitly committed later.
The DBI allows an application to “prepare” statements for
later execution. A prepared statement is identified by a statement
handle held in a Perl variable. We’ll call the Perl variable
$sth
in our examples.
The typical method call sequence for a SELECT
statement is:
prepare, execute, fetch, fetch, ... execute, fetch, fetch, ... execute, fetch, fetch, ...
For example:
$sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?"); $sth->execute( $baz ); while ( @row = $sth->fetchrow_array ) { print "@row\n"; }
The typical method call sequence for a
non-SELECT
statement is:
prepare, execute, execute, execute.
For example:
$sth = $dbh->prepare("INSERT INTO table(foo,bar,baz) VALUES (?,?,?)"); while(<CSV>) { chop; my ($foo,$bar,$baz) = split /,/; $sth->execute( $foo, $bar, $baz ); }
The do()
method can be used for non-repeated, ...
Get Programming the Perl DBI 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.