MySQL Examples& PERL code snippets15 Jun 2006 12:21 pm
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
CODE:
-
$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.
CODE:
-
#Invoke the Perl Database Libraries
-
use DBI;
-
-
-
# MySQL server hostname
-
my $host = "mysql.serverhost.com";
-
-
#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;