MySQL Perl Connection

Connect to MySQL database from Perl

You can connect to MySQL database from a Perl script using the Perl DBI module. DBI stands for "Database Interface" and is a database layer, with simple interface for SQL queries. Here is a Perl script connecting to MySQL database and printing FirstName and LastName columns from a table called Users:


use DBI;

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

$dbh = DBI->connect("dbi:mysql:database=; host=localhost; user=; password=")

or die "Connecting from PHP to MySQL database failed: $DBI::errstr";

$sSQL = "SELECT FirstName, LastName FROM Users";

$st = $dbh->prepare($sSQL)

or die "Preparing MySQL query failed: $DBI::errstr


or die "The execution of the MySQL query failed: $DBI::errstr";

while ($row = $st->fetchrow_hashref())


print " $row->{FirstName} $row->{LastName}


$dbh ->disconnect();