Using a MySQL database from Perl
Archive - Originally posted on "The Horse's Mouth" - 2006-03-13 06:07:20 - Graham EllisBoth Perl and MySQL are major pieces of open source software with a multitude of facilities available - yet you can use them together with just a tiny piece of software "glue" - the DBI and DBD::MySQL module pair from the CPAN (comprehensive Perl archive network).
Once you've got Perl and MySQL installed, the mysqld running, and DBI available to you, inserting data is as easy as connecting to the database:
$cid = DBI -> connect ("DBI:mysql:forsale:192.168.200.66","trainee","abc123");
and running your insert:
$cid->do ("Insert into agents (agent,phone) values ('$ARGV[0]','$ARGV[1]')");
Selecting and displaying records needs a couple more lines of code, since you have to step through ("iterate through") the result set very much like you would read through a file - necessary because the result set may be too big to process all at once. After connecting, prepare and execute your SQL SELECT command:
$action = $cid->prepare("Select agent,phone from agents");
$action->execute();
and you can then step through your result set row by row:
while (@row = $action->fetchrow()) {
print "Call $row[1] to reach $row[0]\n";}
Link - Complete source code of the example that I've quoted from.
We now cover interfacing Perl to databases such as MySQL, and Oracle and Sybase which work through the same mechanism, briefly on our learning to program in Perl course if any of our delegates with to interface to a database. We also cover the subject in more detail on our MySQL and Perl for Larger Projects courses.
A caution - if you're writing a program such as the example I've quoted here that will be used by people other than yourself, you need to add a little extra code to "clean" the user's input - check that it's data that you really want in your database, and that it's not formatted like a piece of malicious SQL to run what's known as an "injection attack"