DBI is a Database Independent Interface for Perl. It provides a standardized API for accessing and updating information in SQL databases.

dBi is used to specify decibels of gain vs an isotropic radiator or antenna.

The DBI is one of the coolest Perl modules. It allows people to connect to any RDBMS and query them with SQL, returning the results in same format. This is very cool compared to database-specific modules - for example, if you want to change the database (move from MySQL to PostgreSQL, for example), all you need to change is the data source definition. (Of course, in "real life", the change isn't that easy. Everything Web System uses DBI too, but it's also heavily tied to MySQL-specific kluges¹. I hope later versions of Everything also run on other RDBMSes.)

You need two module packages: DBI itself, and then a database driver (DBD) for your database; For example, for PostgreSQL, you need DBD::Pg module.

It should be noted that there are DBD modules for "pseudo-databases". Using appropriate driver, you can "connect" to a CSV or plain text file and pretend it's a RDBMS! (Consult CPAN for tons of interesting DBD modules.)

The normal for executing a SQL query via DBI is something like this:

(Side note: Opera's form submission sucks.)

use DBI;

my $username = "drmischief";
my $password = "mUaH4h4H4";

# The data source is a PostgreSQL database 'worlddomination' on localhost

# (See perldoc of your DBD module for data source syntax!)
my $datasource = "DBI:Pg:dbname=worlddomination";

# Connect to the database. Returns a handle.
my $dbconn = DBI->connect($datasource,$username,$password);

# Prepare a query
$dbconn->prepare("SELECT (date, details) FROM schemes;");

# Execute a query

# How many rows were affected?
print $dbconn->rows(), " schemes found.\n";

# Print out the results
my @results;
while(@results = $dbconn->fetchrow_array()) {
    my $date = $results[0];
    my $details = $results[1];

    print "$date: $details\n";

# Finish processing the query

# Disconnect from database.

(I may be slightly rusty and this is from the top of my mind - /msg me if this is just plain wrong.)

¹ Kudos to Nate. My head couldn't stand MySQL for more than a couple of hours... =)

(Also, thanks to m_turner for reminding me about the non-RDBMS DBDs.)

Log in or register to write something here or to contact authors.