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

do( ) Versus prepare( )

As we mentioned in a previous section, the do( ) method supplied by the DBI makes executing non-SELECT statements much simpler than repeatedly preparing and executing statements. This is achieved by simply wrapping the prepare and execute stages into one composite method.

There is a drawback to doing this, however: performance. If you invoked do( ) repeatedly to insert a huge number of rows into a table, you could be preparing a statement handle many times more than is required, especially if the statement contained placeholder variables. For example, the following script inserts some rows into the megaliths table:

### Iterate through the various bits of data...
foreach $name ( qw( Stonehenge Avebury Castlerigg Sunhoney ) ) {
    ### ... and insert them into the table
    $dbh->do( "INSERT INTO megaliths ( name ) VALUES ( ? )", 
              undef, $name );
}

Internally, what happens is that for each row being inserted, a new statement handle is created, and the statement is prepared, executed, and finally destroyed. Therefore, this loop has four prepare calls, four executes, and four destroys. However, since we’re using a bind value for each loop, the database will likely need to parse the statement only once and use that statement again from the Shared SQL Cache. Therefore, in essence, our program is “wasting” three prepares of that statement.

This is a rather inefficient process. In this case, it would be better to hand-prepare and re-execute the statement handle for each iteration ...

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