start page | rating of books | rating of authors | reviews | copyrights

Perl in a Nutshell

Perl in a NutshellSearch this book
Previous: 12.1 DBM Databases and DBM Hashes Chapter 12
Databases and Perl
Next: 12.3 DBI Methods
 

12.2 Design of DBI

If DBM is too primitive for your database requirements, you'll have to use a more sophisticated database package. Options include the commercial products Oracle, Sybase, and Informix, and the publically-available msql and mysql .

Prior to Perl Version 5 and DBI, the problem was that with all the database packages to choose from, there was no way to universalize database support for Perl. You'd have to rebuild the Perl executable itself against libraries that included subroutines for direct access to the database package. For example, sybperl and oraperl are both packages for building Perl Version 4 with Sybase and Oracle calls embedded, respectively. An application written for sybperl would not be portable to Oracle, or vice-versa. However, since current versions of Perl support binary extension loading at runtime, database support can now be added at runtime, which simplifies adding database interfaces to Perl programs while keeping the size of the Perl binary to a minimum.

Support for binary extensions doesn't mean that database access has been standardized. There are still many database extensions to Perl, each with a different API. However, they all share a strikingly similar set of commands: connect to the database, issue queries, fetch results, and disconnect. This consistency has made it possible to develop a standard set of methods to work with any database. DBI defines a set of functions, variables, and conventions that provide a consistent database programming interface for Perl.

Although DBI itself is language-independent, most DBI drivers require applications to use a dialect of SQL (structured query language) to interact with the database engine. SQL is a standard that was developed to allow programmers to manipulate relational databases. There are many implementations of SQL, and each database server adds nuances that deviate from the standard.

12.2.1 Database Drivers (DBDs)

The success of DBI is that it is only half of the story. The other half is a DBD, or a database driver. DBI provides the interface and framework for the drivers, but it's the database drivers that do the real work. Drivers implement the DBI methods for the private interface functions of the corresponding database engine.

Unless you're developing a sophisticated database application, you probably don't care about the drivers except that you want to install the correct one. Table 12.1 lists database servers, where you can find them, and the DBD driver designed for it. (The freeware or shareware database servers are available for download, and some of the commercial servers offer evaluation copies for download.)


Table 12.1: Database Servers
Server URL DBD
DB2 http://www.software.ibm.com/data/db2/ DBD::DB2
Empress http://www.empress.com/ DBD::Empress
Fulcrum http://www.fulcrum.com DBD::Fulcrum
Informix http://www.informix.com/ DBD::Informix
Ingres http://www.cai.com/products/ingres.htm
http://epoch.cs.berkeley.edu:8000/postgres/index.html DBD::Ingres
miniSQL http://www.hughes.com.au/ DBD::mSQL
MySQL http://www.tcx.se/ DBD::mysql
Oracle http://www.oracle.com/ DBD::Oracle
PostgreSQL http://www.postgresql.com/ DBD::Pg
QuickBase http://www.openbase.com/ DBD::QBase
Solid http://www.solidtech.com/ DBD::Solid
Sybase http://www.sybase.com/ DBD::Sybase

12.2.2 Creating a Database

Before you can open a connection to a database with DBI, you must create the database. DBI isn't able to do this step for you, although your DBD might allow you to. For example, DBD:mSQL provides a msqladmin function. Your DBD might also support the func method, which is used to call private (and often non-portable) methods in the driver. You could use a one-liner like this to create the database from the command line:

perl -MDBI -e '$db_name = q[

database_name_here

]; \      $result = DBD::mysql::dr->func($db_name, '_CreateDB');'
If your DBD allows to you to create databases via the API, it's likely that it will allow you to drop them, too.
perl -MDBI -e '$db_name = q[

database_name_here

]; \     $result = DBD::mysql::dr->func($db_name, '_DropDB');'

12.2.3 Database Handles and Statement Handles

DBI methods work on two different types of handles: database handles and statement handles. A database handle is like a filehandle: connect is a DBI class method that opens a connection to a database and returns a database handle object.

$db_handle = DBI->connect(dbi:mSQL:bookdb, undef, undef)     || die("Connect error: $DBI::errstr");
Statement handles are another thing entirely. DBI makes a distinction between the preparation of SQL statements and their execution, by allowing you to pre-format a statement into a statement handle. You can prepare a statement with the prepare method, which returns a statement handle. You can then assign a SQL statement to the statement handle via various statement handle methods, and execute it with the execute method when you're done. (You can also prepare and execute in the same command with the do method.)

Changes to the database are written to the database automatically if the AutoCommit attribute is turned on. If AutoCommit is off, then use the commit method when you're ready to write the changes to the database.

AutoCommit is only one of many attributes that can be set for both database and statement handles. For example, if $st_handle is a statement handle, then you can set $st_handle->{NULLABLE} to determine if the fields can contain null characters. Table 12.2 is a listing of all the attributes supported by database handles, statement handles, or both.


Table 12.2: Attributes for Database and Statement Handles
Attributes for database handles
AutoCommit

Commit any changes to the database immediately, instead of waiting for an explicit call to commit . Default is true.

Attributes for statement handles
CursorName

The name of the cursor associated with the statement handle.

NAME

A reference to an array of field names.

NULLABLE

A reference to an array describing whether each field can contain a null character.

NUM_OF_FIELDS

Number of fields the prepared statement will return.

NUM_OF_PARAMS

Number of placeholders in the prepared statement.

Attributes common to all handles
Warn Enables warnings.
CompatMode Enables compatible behavior for a specific driver.
InactiveDestroy

Destroying a handle does not close prepared statements or disconnect from the database.

PrintError Errors generate warnings.
RaiseError Errors raise exceptions.
ChopBlanks

Truncate trailing space characters in fixed-width character fields.

LongReadLen

Controls the maximum length of long data.

LongTruncOk

Controls whether fetching long data that has been truncated should fail.

12.2.4 Placeholders database and statement handles

Many database drivers allow you to use question marks as placeholders in SQL statements, and then bind values to the placeholders before executing them. This enables you to prepare a single statement with placeholders and then reuse it for each row of the database. For example, the prepare statement might read:

$st_handle = $db_handle->prepare(q{ 	insert into books (isbn, title) values (?, ?) })  || die db_handle->errstr;
And a subsequent execute statement might read:
$st_handle->execute("1-56592-286-7", "Perl in a Nutshell")  	|| die $db_handle->errstr;


Previous: 12.1 DBM Databases and DBM Hashes Perl in a Nutshell Next: 12.3 DBI Methods
12.1 DBM Databases and DBM Hashes Book Index 12.3 DBI Methods

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.