Skip to search.

Breaking News Visit Yahoo! News for the latest.

×Close this window

Search Help:  
 
Enter keywords to search help.

How can I access my database using Perl?

You can connect Perl to your MySQL database account using the DBI Perl module. For more information on this Perl module and how to query MySQL, please visit the MySQL web site.

Below is a sample Perl script that will enable you to connect to a database. Please note that you will need to change the user (database user name), pass (database password), and db (database name) values in this script.

#!/usr/bin/perl -w

use DBI;

print "Content-type: text/html\n\n";

## user database name
$db ="mysql";
## database user name
$user = "XXXX";
## database password
$pass = "XXXX";

## user hostname : This should be "mysql"
$host="mysql";

## SQL query
$query = "show tables";

$dbh = DBI->connect("DBI:mysql:$db:$host", $user, $pass);
$sth = $dbh->prepare($query)
or die "Can't prepare $query: $dbh->errstr\n";

$rv = $sth->execute
or die "can't execute the query: $sth->errstr";

print "<h1>Perl DBI Test</h1>";
print "<p>Here is a list of tables in the database $db.</p>";
while (@row= $sth->fetchrow_array()) {
my $tables = $row[0];
print "$tables\n<br>";
}

$rc = $sth->finish;
exit(0);

To learn more about MySQL, please visit the MySQL web site or browse books about MySQL.

To learn more about Perl, we suggest visiting http://www.perl.org or getting a book on Perl.

Was this article helpful?

Yes   No
Click to contact Customer Care for further assistance.