Pages

Hello DBI

The most commonly used Perl module to access database is DBI. Once installed this Perl module on my current machine (I simply opened a cpan shell and I entered the command "install DBI" and I let cpan doing its dirty job - obviously an active connection to the internet is required). I wrote a silly little perl script to test everything works fine.

This code just open a connection to a mysql database, and then it close it:

#!/usr/bin/perl
use strict;
use warnings;
use DBI;

my $dbh = DBI->connect("dbi:mysql:test", "root", "password") ||
die "Connection error: $DBI::errstr\n";

$dbh->disconnect();
print "Done.";

There is something interesting even in these few lines.

First of all we see that to start a connection we call the connect() function in the DBI package passing three paramenters representing the database to which we are about to connect (protocol and database name), the database user and its password.

If connect() fails, we let our script die, showing the error message that is stored in DBI::errstr.

Finally (!) we close the connection calling the disconnect() method on the dbh object resulting by the connect() call.

No comments:

Post a Comment