Perl: Connect to a MySQL Database
This tip includes sample code that shows how to connect to a mySQL database with a Perl script. There are a number of steps necessary before you can even try this sort of script.
Installation
Before you can try the script, you must first install Perl and MySQL. You can get MySQL from the their site by clicking here. For Perl on Windows, I recommend Active State's Perl distribution. You can find download the latest version from their site by clicking here.
Creating a test database
Next, you'll need to create a test database in MySQL. The steps for creating the database used in this how to are described in this MySQL how to.
Installing Perl Modules
Next, you need two Perl database modules to access a database. First the DBI module adds database extensions. Then the DBD module specific to your database.
ActiveState Perl comes with a cool tool for installing Perl modules. Switch to c:\perl\bin directory and run the ppm.bat file. This runs the Perl Package Manager which allows you to install Perl modules from the Internet.
Issue the following two commands from PPM to install the necessary database drivers for mySQL.
PPM> install DBI
PPM> install DBD-Mysql
The Database Script
Here is the Perl script to access the data.
Executing the Script
Executing the script from the command line should produce output similar to that shown below.
C:\da\Perl> perl guestdb.pl Name: Test User1 EMail: testuser@test.com msgFrom: Smallville USA Name: Test User2 EMail: testuser2@test.com msgFrom: Smalltown USA Name: Test User3 EMail: testuser3@test.com msgFrom: Smallcity CA Name: Test User4 EMail: testuser4@test.com msgFrom: LittleTown CO