- Web Database Interaction Using Perl
- Form Access with CGI.pm
- Checking Variables with Regular Expressions
- Accessing a Database with DBI.pm
- Error Handling
- About This Article
Accessing a Database with DBI.pm
In this example, any database that is visible to Perl is available to the query processor. The module that provides this functionality is DBI.pm. This module unites a number of secondary database drivers (called DBD modules) under a common object structure and method syntax. DBI is a boon to Web application programmers because it enables database-generic code to be used with any database without modification. This comes in handy when developing a prototype using an inexpensive database system, such as PostgreSQL, and transferring the resultant programs to a production database, such as Oracle.
Because DBI offers connections to many databases, the query processor needs a way to indicate which database and data source the query is intended to access. DBI provides convenience methods for enumerating available database drivers and data sources. So, lines 029 and 032 use the available_drivers and data_sources methods to get lists of possible data sources available. (An eval block catches errors from the available_drivers method; DBI installs many drivers by default. Not all drivers apply to every system running this program.) DBI takes these data sources as connection strings in the same form in which they are given by the data_sources method. Therefore, it's possible to list the sources without any translation or parsing.
After a data source is chosen and a query is submitted, lines 079 to 089 pass the query to the specified data source, and lines 098 to 121 format the output in as generic a way as possible. This is assisted by the NAME attribute of the statement handle $sth used in line 96, which references a list of the field names returned by the query. By listing these names as headings in an HTML table in lines 103 to 106, you can provide an understandable view of the results without knowing in advance either their size or contents.