Search

FAQ > MySQL

How do I connect to MySQL with Perl?

#!/Applications/MAMP/Library/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`");
my $out = $sql->execute()
or die "Unable to execute sql: $sql->errstr";

while ((my $id, my $name) = $sql->fetchrow_array()) {
  print "id: $id / name: $name<br>";
}

$dbc->disconnect();