1

I am having issues getting a simple DBI connection using perl to work.

I put a place checker to see if the database handle is undefined and it always comes out undefined. Are there any blatant errors? I'm assured that the info I enter is correct, as I'm using it in a php script.

#!/usr/bin/perl -w
use warnings;
print "Content-Type: text/html\n\n";

use DBI;

# Connecting to the database
# Replace DATABASENAME with the name of the database,
# HOSTNAME with the hostname/ip address of the MySQL server.
$drh = DBI->install_driver("mysql");
$dsn =   "DBI:mysql:database=db_name;host=host_name";
$dbh = DBI->connect($dsn,"username","password");
if(defined $dbh)
{
    print "Yes<br />";
}
else
{
    print "No<br />";
 }

 # Select the data and display to the browser

   $sth = $dbh->prepare("SELECT * FROM customer");
   $sth->execute();
   while (my $ref = $sth->fetchrow_hashref()) {
   print "Found a row: id = $ref->{'cid'}";
}

$sth->finish();

# Disconnect from the database.

$dbh->disconnect();
2
  • 2
    What happens if you connect() with { RaiseError => 1 } ? Commented Aug 23, 2012 at 20:23
  • $drh = DBI->install_driver("mysql"); is useless Commented Aug 23, 2012 at 20:24

1 Answer 1

6

An error occured if connect returned undef. Throw some error handling in there. It might give you some useful information.

$dbh = DBI->connect($dsn, $user, $pw)
   or die "Unable to connect: $DBI::errstr\n";
Sign up to request clarification or add additional context in comments.

5 Comments

When I add the following or die to the code it does not print the statement afterwards? I have feeling something is messed up with perl, but wouldn't know where to start. $dbh = DBI->connect($dsn,"username","pw") or die "Unable to connect: $DBI::errstr\n"; print "why";
It's unlikely that the problem is with perl. Can you manually connect to the database? Are all you parameters you're sending correct? Add a 'use strict' to your code too.
I ran your code, with the added 'die' statement, on my machine and received an error.
The use strict helped determine the issue. It turns out it was evaluating part of the variables in the database handle and making those single quotes prevented that! Thanks!
Great. You should always use 'use strict'. It will save you a lot of headaches.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.