Perl (Scripting) - Connect to a SQL database

by
Jeremy Canfield |
Updated: March 09 2020
| Perl (Scripting) articles
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();
Did you find this article helpful?
If so, consider buying me a coffee over at