Contents Perl  MySQL Module

PERL - MySQL Module

MySQL queries and the like can be executed with PERL via the MySQL Module. This module should already be installed with your web server if not contact your web host.

As a quick overview, this module installs the necessary functions required to execute MySQL queries using a PERL script. Please take note that this module only works with the MySQL platform. Other SQL platforms will require the use of the DBI module discussed in our PERL DBI Module lesson.

PERL - MySQL Config

Before we dive head first into the functions, we may want to set up some config variables that we will be calling upon in each script to first connect to our database. Have the following information easily accessible.

  • Our Web Host's data source name (DSN)
  • User Name for the MySQL Database
  • Password for the MySQL Database
  • Name of Database
  • Name of Table(s)

perlmysqlconfig.pl:

#!/usr/bin/perl

# PERL MODULE WE WILL BE USING
use Mysql;

# MySQL CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";

A config set-up like this simplifies our connection script and the queries that will be executed later.

PERL - MySQL Connect

The MySQL module works only with the MySQL platform. We can maintain the same variables from the previous example to connect to MySQL.

perlmysqlconnect.pl:

#!/usr/bin/perl

# PERL MODULE
use Mysql;

# HTTP HEADER
print "Content-type: text/html \n\n";

# CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";

# PERL MYSQL CONNECT
$connect = Mysql->connect($host, $database, $user, $pw);

If this script was run on your web server through a web browser, you should be starring at a blank white screen and all is well.

PERL - MySQL listdbs()

Once PERL has established a connection we can execute any of the built in module functions. A great introductory function is the listdbs function. This function reads from the MySQL platform and places the name of each database into an array.

listdbs.pl:

@databases = $connect->listdbs;

We can then loop through this array and print out our results to the browser.

listdbs2.pl:

#!/usr/bin/perl

# PERL MODULES
use Mysql;

# MYSQL CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";

# PERL CONNECT()
$connect = Mysql->connect($host, $database, $user, $pw);

# LISTDBS()
@databases = $connect->listdbs;
foreach $database (@databases) {
	print "$database<br />";
}
 
 

    

Want Some more information and Video ???

 

Home