How to work with MySQL from Perl scripts.


To work with MySQL from Perl scripts, the DBI module is usually used. This allows you to conveniently open and close DBMS connections, prepare and execute database queries, handle errors, and so on. If you have no experience working with MySQL from Perl.


So, an example of working with MySQL from Perl DBI:


#!/usr/bin/perl

use DBI;

my $host = "localhost"; # MySQL server
my $port = "3306"; # port to which we open the connection
my $user = "u12345"; # username (fictitious)
my $pass = "password"; # password
my $db = $user; # database name -by default is equal to the user name

print "Content-type: text/htmlnn";

$dbh = DBI->connect("DBI:mysql:$db:$host:$port",$user,$pass);
$sth = $dbh->prepare("select field1 from table2");#preparing the request
$sth->execute; # executing the request

while ($ref = $sth->fetchrow_arrayref) {
print "$$ref[0]n"; # print the result
}

$rc = $sth->finish; #close
$rc = $dbh->disconnect; # connection

In this example, we first define variables with MySQL access parameters, then issue an HTTP header, since this is our script to run via the web, then connect to the database, prepare and send a select request, receive and print the results, and then close the connection. This is the simplest script for working with MySQL from Perl.