Connecting to the MySQL Server and Database
To access the MySQL server from a Perl script, we need the DBI module discussed in Setting up Perl” in Chapter 2. In the script, we must tell Perl that we want to use this module:
use DBI;
Then, we provide connection
parameters to the DBI connect() function and store the
returned connection in a database handler (dbh):
my $dbh=DBI->connect("DBI:mysql:host=localhost;database=mysql",
"the_username",
"the_password");For a Mac OS X server using the XAMPP Perl installation, you would write:
my $dbh=DBI->connect("DBI:mysql:
host=localhost;mysql_socket=/Applications/xampp/xamppfiles/var/mysql/mysql.sock;
database=mysql",
"the_username",
"the_password"); Don’t add a new line before
the database=mysql parameter; we
had to do this so that the instruction would fit on the page. If you
followed our XAMPP installation instructions in Installing Perl modules under Mac OS X” in Chapter 2 to create a
symbolic link to the default MySQL socket file location
(/tmp/mysql.sock), you can omit the mysql_socket parameter.
We can follow this with Perl instructions to carry out the main functions of the script. Finally, being good citizens, we disconnect from the server before we end the script:
$dbh->disconnect();
The arrow (arrow -> operator) operator is used to call
functions that are associated with a class of objects. In the
connection code, we’ve called on the connect() function of the DBI class. We also call on functions associated with the database handler ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access