User Tools

Site Tools


classes:general:dbsamples:perl_mysql

Perl example for MySQL database connection

use strict;
use DBI qw(:sql_types);

# Variables
my $db_conn_string;                                 # MySQL db connection string
my $db_name = "dbname";                             # Database name
my $db_user = "remoteUser";                         # Database user
my $db_pwd  = "bigsecurepassword";                  # Database pwd
my $db_host = "host.cs.ndsu.nodak.edu";             # Database server host name
my $db_port = "3306";                               # Database connection port
my $conn;                                           # MySQL connection
my $stmt;                                           # MySQL statement

# Connect to MySQL database

$db_conn_string = "dbi:mysql:$db_name:$db_host:$db_port";

# Connect to db 
if ($conn = DBI->connect($db_conn_string, $db_user, $db_pwd))
{
  # Prepare and execute an SQL statement
  $stmt = $conn->prepare("SELECT table_name.column_name
                          FROM table_name
                          WHERE table_name.field=something");
  $stmt->execute;

  # Retrieve the results

  print "Query Output \n";
  while(my $ref = $stmt->fetchrow_hashref() ) {
	print $ref->{'column_name'};
	print "\n";
  }
}
else
{
  # Error! Couldn't connect to MySQL db
}
classes/general/dbsamples/perl_mysql.txt · Last modified: 2021/09/17 17:27 by localadmin