This article describes two methods for connecting to a MySQL database using Perl:
Using the DBI module is the preferred way to connect to MySQL in Perl. The original Perl mysql module is deprecated.
To connect to MySQL using the DBI module, follow these steps:
use DBI; $myConnection = DBI->connect("DBI:mysql:DBNAME:localhost", "USERNAME", "PASSWORD");
After the code connects to MySQL and selects the database, you can run SQL queries and perform other operations. For example, the following Perl code runs a SQL query that extracts the last names from the employees table, and stores the result in the $result variable:
$query = $myConnection->prepare("SELECT lastname FROM employees"); $result = $query->execute();
The original Perl mysql module is deprecated, and should only be used when absolutely necessary for backward compatibility. If possible, use the DBI module instead.
To connect to MySQL using the legacy mysql module, follow these steps:
use Mysql; $myConnection = Mysql->connect('localhost','DBNAME','USERNAME','PASSWORD');
After the code connects to MySQL and selects the database, you can run SQL queries and perform other operations. For example, the following Perl code runs a SQL query that extracts the last names from the employees table, and stores the result in the $result variable:
$result = $myConnection->query('SELECT lastname FROM employees');
To view the online documentation for the DBI module, please visit http://dbi.perl.org/docs.
Subscribe to receive weekly cutting edge tips, strategies, and news you need to grow your web business.
No charge. Unsubscribe anytime.
Did you find this article helpful? Then you'll love our support. Experience the A2 Hosting difference today and get a pre-secured, pre-optimized website. Check out our web hosting plans today.
We use cookies to personalize the website for you and to analyze the use of our website. You consent to this by clicking on "I consent" or by continuing your use of this website. Further information about cookies can be found in our Privacy Policy.