Skip to content
MAMP PRO Documentation

How do I connect to MySQL with Perl?

#!/usr/bin/perl
use strict;
use warnings;
use DBI;
print "Content-type: text/html\n\n";
my $source = 'DBI:mysql:test:localhost'; # format = DBI:mysql:database:hostname
my $user = 'root';
my $password = 'root';
my %attr = (
PrintError => 0, # turn off error reporting via warn()
RaiseError => 1, # turn on error reporting via die()
);
my $dbc = DBI->connect($source, $user, $password, \%attr)
or die "Unable to connect to mysql: $DBI::errstr\n";
my $sql = $dbc->prepare("SELECT `id`, `name` FROM `test`");
$sql->execute()
or die "Unable to execute sql: " . $sql->errstr;
while ((my $id, my $name) = $sql->fetchrow_array()) {
print "id: $id / name: $name<br>";
}
$sql->finish();
$dbc->disconnect();

MySQL how-to guides