Access your MySQL Database with Perl

Share this article

One of the most common Perl-related questions at the SitePoint Forums is, “How do I access my database with Perl?” Perl can work with nearly every type of database on the market, but today I’ll use MySQL as an example.

For the purposes of this demonstration, let’s say we have a database named “shoes” with one table named “subscribers”. Here’s the layout of the table:

create table subscribers (
uid int not null primary key auto_increment,
username varchar(32) not null,
emailaddr varchar(32) not null
);

We will connect to MySQL with the DBI modules and the DBD::mysql database driver. These modules don’t come with the standard Perl distribution, so you’ll have to obtain them yourself. If you maintain your own server, follow the instructions below, but if you have a Web host, they should be able to take care of the installation for you, if they don’t already have the modules installed.

Install the Modules

To install the DBI and DBD::mysql modules on a Unix-like OS or Perl on Windows installed as part of Cygwin, run the following commands.

Note that you must have MySQL already installed or you will not be able to install the DBD::mysql module. Also, if you haven’t installed any other modules this way, you’ll be asked for configuration options. Luckily, these are self-explanatory. Once you’ve finished entering the configuration values, the module installation will start.

perl –MCPAN –e 'install DBI'
perl –MCPAN –e 'install DBD::mysql'

You’ll see several screens of text fly by, but eventually it should return you to the friendly command prompt.

There will rarely be any errors, because these modules have been tested by thousands of people. However, if you are unlucky enough to encounter errors, a quick search on Google will probably find you the solution.

Work with the Database


Now that the modules and database drivers are installed, we can progress to the actual Perl code to work with the database. For now we’ll just connect to the database.

# set the data source name
# format: dbi:db type:db name:host:port
# mysql's default port is 3306
# if you are running mysql on another host or port,
#    you must change it
my $dsn = 'dbi:mysql:shoes:localhost:3306';
 
# set the user and password
my $user = 'user';
my $pass = 'pass';
 
# now connect and get a database handle  
my $dbh = DBI->connect($dsn, $user, $pass)
 or die "Can't connect to the DB: $DBI::errstrn";

OK, there were a lot of new things in that code. First, we defined the DSN, or data source name. This tells the DBI where to find your database server, and what database you will operate on. Then, we set the username and password to connect to the database as. Finally, we call DBI->connect to actually connect to the database (don’t forget to enter your own username and password!), and if the connection was unsuccessful, we print out an error. From that command, we get a database handle, which we will use to run queries on the database.

The execution of a query takes two steps: preparation and execution. First, you must prepare the query like this:

my $sth = $dbh->prepare('insert into subscribers(username, emailaddr)
values "jim", "jim@microsoft.com")');


Then you can execute it:

$sth->execute();
Because we ran an INSERT query, there weren’t any results to retrieve. But what if we used SELECT? How would we get the data? Like this:

my $sth = $dbh->prepare("select username, email from subscribers");
$sth->execute;
 
while(@row = $sth->fetchrow_array()) {
 print "$row[0]: $row[1]<br>";
}

As you can see, $sth->fetchrow_array returns an array of the results. If you like, you could write the loop like this to make it a bit more readable:

while(my($username, $email) = $sth->fetchrow_array()) {
 print "$username: $email<br>";
}

Instead of assigning the values to a normal array, this assigns the rows’ values each to a different variable.

Build the Web App

Now let’s use the DBI to create a (somewhat) useful Web application to manage catalog subscribers of a fictitious shoe store. There will be two pages, view.pl and add.pl, and the database schema will be the same as the one at the top of this guide. Again, remember that you have to enter your own username and password in these scripts instead of the default “user” and “pass”.

Here is add.pl:

use CGI;  
use DBI;  
 
print CGI::header();  
 
my $username = dbquote(CGI::param('name'));  
my $email    = dbquote(CGI::param('email'));  
 
unless($username) {  
 print <<PAGE;  
<h1>Add a Subscriber</h1>  
<form action=add.pl method=post>  
Name: <input type=text name=name><br>  
Email: <input type=text name=email><br>  
<input type=submit value="Add Subscriber">  
</form>  
PAGE  
 
exit;  
}  
 
# connect  
my $dbh = DBI->connect("dbi:mysql:shoes:localhost:3306", "user", "pass");  
 
# prepare the query  
my $sth = $dbh->prepare("insert into subscribers(username, emailaddr)  
values('$username', '$email')");  
 
# execute the query  
$sth->execute();  
 
print <<PAGE;  
<h1>User Added</h1>  
The user $username was just added.  Want to  
<a href=add.pl>add another</a>? PAGE  
 
sub dbquote {  
 my($str) = @_;  
   
$str =~ s/"/\"/g;  
 $str =~ s/\/\\/g;  
 $str =~ s/'/\'/g;  
 
 return $str;  
}

And here is view.pl:
use DBI;  
use CGI;  
 
print CGI::header();  
 
print "<h1>Subscribers</h1>";  
 
# connect  
my $dbh = DBI->connect("dbi:mysql:shoes:localhost:3306", "user", "pass");  
 
# prepare the query  
my $sth = $dbh->prepare("select username, emailaddr from subscribers");  
 
# execute the query  
$sth->execute();  
 
while(my ($username, $email) = $sth->fetchrow_array()) {  
 print "$username: $email<br>n";  
}

That's it! If you're after more information, try these resources:

Frequently Asked Questions (FAQs) about Accessing MySQL Database with Perl

How can I install the DBI and DBD::mysql modules in Perl?

To access MySQL database using Perl, you need to install two modules: DBI and DBD::mysql. DBI is the standard database interface for Perl, and DBD::mysql is the driver that allows Perl to connect with the MySQL database. You can install these modules using the CPAN (Comprehensive Perl Archive Network). Open your terminal and type cpan DBI to install the DBI module and cpan DBD::mysql to install the DBD::mysql module. Follow the prompts to complete the installation.

How can I connect to a MySQL database using Perl?

To connect to a MySQL database, you need to use the connect method provided by the DBI module. This method requires four arguments: the Data Source Name (DSN), the username, the password, and the attribute hash reference. The DSN includes the type of the database, the name of the database, and the host. Here is an example of how to use the connect method:

my $dsn = "DBI:mysql:database_name:host_name";
my $username = "your_username";
my $password = "your_password";
my $dbh = DBI->connect($dsn, $username, $password, {'RaiseError' => 1});

How can I execute SQL queries using Perl?

To execute SQL queries, you need to use the prepare and execute methods provided by the DBI module. The prepare method takes an SQL statement as an argument and returns a statement handle object. The execute method is then called on this object to execute the SQL query. Here is an example:

my $sth = $dbh->prepare("SELECT * FROM table_name");
$sth->execute();

How can I fetch data from a MySQL database using Perl?

After executing an SQL query, you can fetch the data using the fetchrow_array method. This method returns the next row of data as an array. You can use a while loop to fetch all rows. Here is an example:

while (my @row = $sth->fetchrow_array()) {
print "@row\n";
}

How can I handle errors when accessing a MySQL database using Perl?

The DBI module provides several methods to handle errors. The RaiseError attribute in the connect method will cause the program to die if any DBI method fails. You can also use the err method to get the native database engine error code and the errstr method to get the error string. Here is an example:

if (!defined $dbh) {
die "Error connecting to the database: " . DBI->errstr;
}

How can I disconnect from a MySQL database using Perl?

To disconnect from a MySQL database, you need to use the disconnect method. This method is called on the database handle object. Here is an example:

$dbh->disconnect();

How can I insert data into a MySQL database using Perl?

To insert data into a MySQL database, you need to use the do method. This method takes an SQL statement as an argument and executes it. Here is an example:

$dbh->do("INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')");

How can I update data in a MySQL database using Perl?

To update data in a MySQL database, you need to use the do method with an UPDATE SQL statement. Here is an example:

$dbh->do("UPDATE table_name SET column1 = 'new_value' WHERE condition");

How can I delete data from a MySQL database using Perl?

To delete data from a MySQL database, you need to use the do method with a DELETE SQL statement. Here is an example:

$dbh->do("DELETE FROM table_name WHERE condition");

How can I create a MySQL database using Perl?

To create a MySQL database, you need to use the do method with a CREATE DATABASE SQL statement. Here is an example:

$dbh->do("CREATE DATABASE database_name");

Quinn SlackQuinn Slack
View Author

Quinn is a Perl coder and Mentor (known as "qslack") for the Build team in the SitePoint Forums.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form