Skip to Main Content
Programming the Perl DBI
book

Programming the Perl DBI

by Tim Bunce, Alligator Descartes
February 2000
Intermediate to advanced content levelIntermediate to advanced
364 pages
11h 47m
English
O'Reilly Media, Inc.
Content preview from Programming the Perl DBI

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, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced Perl Programming, 2nd Edition

Advanced Perl Programming, 2nd Edition

Simon Cozens
Perl One-Liners

Perl One-Liners

Peteris Krumins
Advanced Perl Programming

Advanced Perl Programming

Sriram Srinivasan
Beginning Perl

Beginning Perl

Curtis Ovid Poe

Publisher Resources

ISBN: 1565926994Supplemental ContentErrata Page