Using the DBI Framework

Here are the basic steps for using DBI. For more information on DBI, see Developing the Perl DBI by Alligator Descartes and Tim Bunce (Anonymous).

DBI Leftovers

There are two remaining DBI topics worth mentioning before we move on to ODBC. The first is a set of methods I call "shortcut" methods. The methods in Table 7-2 combine steps 3 and 4 from above.

Table 7.2. DBI Shortcut Methods

Name Combines These Methods into a Single Method
selectrow_arrayref($stmnt) prepare($stmnt), execute(), fetchrow_arrayref( )
selectcol_arrayref($stmnt) prepare($stmnt), execute(), (@{fetchrow_arrayref( )})[0] (i.e., returns first column for each row)
selectrow_array($stmnt) prepare($stmnt), execute(), fetchrow_array( )

The second topic worth mentioning is DBI's ability to bind variables to query results. The methods bind_col( ) and bind_columns( ) are used to tell DBI to automatically place the results of a query into a specific variable or list of variables. This usually saves a step or two when coding. Here's an example using bind_columns( ) that makes its use clear:

$sth = $dbh->prepare(q{SELECT name,ipaddr,dept from hosts}) or die "Unable to prep our query:".$dbh->errstr".\n"; $rc = $sth->execute or die "Unable to execute our query:".$dbh->errstr".\n"; # these variables will receive the 1st, 2nd, and 3rd columns # from our SELECT $rc = $sth->bind_columns(\$name,\$ipaddr,\$dept); while ($sth->fetchrow_arrayref){ # $name, $ipaddr, and $dept are automagically filled in from # the fetched query results row do-something-with-the-results }