Other Applications: Perl

  1. Python
  2. Other Applications

Perl requires the DBI database interface to connect to MySQL. You can get it from CPAN:

perl -MCPAN -e shell

install dbi

install DBD::mysql

This will get you the DBI interface and the MySQL information it needs to work.

The DBI interface is object-oriented, and returns handles to various objects or arrays. In Perl, queries must be “prepared” before they are executed. The fetchrow_hashref() method is the equivalent of PHP’s mysql_fetch_array() function. It returns a handle to an associative array. You need to dereference the handle using double dollar signs.

#!/usr/bin/perl

use DBI;

$driver = "mysql";

$host = "localhost";

$port = 3306;

$user = "Username";

$pass = "Password";

$database = "music";

$query = "SELECT album, artist, year, rating FROM albums ORDER BY artist";

$dataSource = "DBI:$driver:database=$database;host=$host;port=$port";

print "<html>\n";

print "<head><title>My Albums</title></head>\n";

print "<body>\n";

print "<h1>My Albums</h1>\n";

print "<table>\n";

print "<tr><th>Album</th><th>Artist</th><th>Year</th><th>Rating</th></tr>\n";

if ($databaseHandle = DBI->connect($dataSource, $user, $pass)) {

if ($queryHandle = $databaseHandle->prepare($query)) {

if ($queryHandle->execute) {

while ($rowHandle = $queryHandle->fetchrow_hashref()) {

$album = $$rowHandle{'album'};

$artist = $$rowHandle{'artist'};

$year = $$rowHandle{'year'};

$rating = $$rowHandle{'rating'};

print "<tr>";

print "<th>$album</th><td>$artist</td><td>$year</td><td>$rating</td>";

print "</tr>\n";

}

} else {

print "Unable to execute query $query: $!\n";

}

$queryHandle->finish;

} else {

print "Unable to prepare query $query: $!\n";

}

$databaseHandle->disconnect;

} else {

print "Unable to connect to data souce $dataSource: $!\n";

}

print "</table>\n";

print "</body>\n";

print "</html>\n";

  1. Python
  2. Other Applications