How to make a connection to a SQL database in Perl

Home > Search > How-to
  by

If not already installed, install the DBI and database specific modules. For example, if connecting to a MySQL database, you would install DBI and Net::MySQL. Or, if running Perl on Linux, the following packages can be installed.

# Red Hat
yum install perl-DBD-mysql

# Debian
apt-get install libdbd-mysql-perl

 

Then, use the following markup to make a connection to a database (MySQL in this example).

use DBI;
 
my $dbconnect = DBI->connect("DBI:mysql:database=database_name;host=database_hostname",
                                        "username","password",
                                        {'RaiseError' => 1});
 
my $statement = $dbconnect->prepare("select * from foo");
$statement->execute();
while (my $ref = $statement->fetchrow_hashref()) {
  print "$ref->{'id'}\n";
  print "$ref->{'name'}\n";
  print "$ref->{'date'}\n";
}

$statement->finish();
$dbconnect->disconnect();

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments