2

I have connected to one MySQL database which have been hosted in a remote server in Perl. Now I am trying to execute a select statement on a table in subject.pl file using Perl command line. The code is

#!/usr/bin/perl

use DBI;
use strict;

# Connected to mysql audit database in dev server
my $dsn = 'DBI:mysql:Driver={mysql}';
my $host = 'dev-mysql.learn.local';
my $database = 'subject';
my $user = 'testUser';
my $auth = 'testPassword';
my $dbh = DBI->connect("$dsn;host=$host;Database=$database",$user,$auth) or die            "Database connection not made: $DBI::errstr";

# Prepare query
my $sql = "SELECT
        subject_id
        ,subject_value
    FROM
        subject";
my $sth = $dbh->prepare($sql);

#Execute the statement
$sth->execute() or die "Unable to execute".$sth->errstr;

while (my @row = $sth->fetchrow_array()) {
   my ($subject_id, $subject_value ) = @row;
   print "$subject_id,$subject_value,$subject_db_field\n";
}

$sth->finish();

I am getting error at line $sth->execute() or die "Unable to execute".$sth->errstr;

The error message is Unable to execute at D:\Demo\perl_demo\subject.pl line 24.

But when I am printing the $dbh variable, its giving the result like DBI::db=HASH(0x1ca7884). So I guess the connection is establishing properly.

Please help me to fix this issue as I am completely new in Perl scripting.

3
  • 1
    Did you check the return value of $dbh->prepare($sql) ? Commented Nov 21, 2013 at 8:04
  • you surely have connection as otherwise it would die at connect (connect.. or die ..) Commented Nov 21, 2013 at 8:23
  • Yes Frank, I have checked the return value of $dbh->prepare($sql). Its giving DBI::db=HASH(0x1ca74f4) Commented Nov 21, 2013 at 8:55

1 Answer 1

1

Check for errors on prepare,

my $sth = $dbh->prepare($sql) or die $dbh->errstr;
Sign up to request clarification or add additional context in comments.

6 Comments

I have checked with pitting your code. But its not throwing any error. When I print the $sth variable, its giving result like DBI::db=HASH(0x1ca74f4)
@KanhuCharanSahu it is strange that $sth->execute() or die $sth->errstr; doesn't report actual error message?
is it due to the remote database?
@KanhuCharanSahu no, DBI should always have error message when something fails.
@KanhuCharanSahu you can set {RaiseError => 1} as fourth argument to connect
|

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.