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:
  1. $perl -MCPAN -e shell
  2. $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:
  1. #Invoke the Perl Database Libraries
  2. use DBI;
  3.  
  4.  
  5. # MySQL server hostname
  6. my $host = "mysql.serverhost.com";
  7.  
  8. #your account username and MySQL password
  9. my $username = "your_user";
  10. my $password = "your_MySQL_password";
  11.  
  12.  
  13. #Edit this to point to the database you wish to connect to
  14. my $db_name = "your_database";
  15.  
  16.  
  17. #
  18. #The following lines do not need to be edited
  19. #
  20. #put the database and server in to the connect statement
  21. $dsn = "DBI:mysql:database=$db_name;host=$host";
  22.  
  23.  
  24. #Generate the full connect statement
  25. $dbh = DBI->connect($dsn, $username, $password);
  26.  
  27.  
  28. #run the connect statement
  29. $self->dbh = $dbh;