Press "Enter" to skip to content

Perl MySQL Connect

Like all programing languages, there are many ways to connect to databases, this in particular shows a the simplest method, though burying the host, username and password in an include would be better for security reasons, this is effective enough for most purposes.

The only requirements for perl may be the DBD::mysql module if not already installed, this should get all the needed prerequisites that may not be present. Either download them directly from CPAN or use the interactive installer shell

$perl -MCPAN -e shell
$install DBD::mysql

To use this example copy this code into your script, edits $username, $password, and $db_name values to suit your environment.

#Invoke the Perl Database Libraries
use DBI;

# MySQL server hostname
my $host = “”;

#your account username and MySQL password
my $username = “your_user”;
my $password = “your_MySQL_password”;

#Edit this to point to the database you wish to connect to
my $db_name = “your_database”;

#The following lines do not need to be edited
#put the database and server in to the connect statement
$dsn = “DBI:mysql:database=$db_name;host=$host”;

#Generate the full connect statement
$dbh = DBI->connect($dsn, $username, $password);

#run the connect statement
$self->dbh = $dbh;