Bootstrap FreeKB - Perl (Scripting) - Connect to a SQL database
Perl (Scripting) - Connect to a SQL database

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


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