About Linux FAQ

Browse More FAQs:

How to access MySQL database using Perl

Posted by Vivek Gite [Last updated: December 21, 2006]

Q. How do I access my MySQL database server using Perl programming language?

A. DBI is a generic interface for many databases. That means that you can write a script that works with many different database engines without change. You need a DataBase Driver (DBD) defined for each database type. For MySQL, this driver is called DBD::mysql.

So you can connect Perl to your MySQL database server using the DBI Perl module. Here is small program.

Sample Perl code

Make sure you replace database name, MySQL server hostname, username and password according to your setup.

!/usr/bin/perl -w

use DBI;

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

## mysql user database name
$db ="mysql";
## mysql database user name
$user = "vivek";

## mysql database password
$pass = "myPassword";

## user hostname : This should be "localhost" but it can be diffrent too
$host="localhost";

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

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

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

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

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

Save and upload above program.

Subscribe to our free e-mail newsletter or RSS feed to get all updates. You can Email this page to a friend.

Related Other Helpful FAQs:

Leave a Reply

We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Copyright © 2006-2008 nixCraft. All rights reserved - TOS/Disclaimer - Privacy policy - Sitemap - Powered by Open source software.