2013-11-21 55 views
2

我已連接到一個已在遠程服務器中託管的MySQL數據庫。現在我正在嘗試使用Perl命令行在subject.pl文件的表上執行select語句。該代碼是無法在連接到遠程服務器時在perl中執行mysql查詢

#!/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(); 

我在行$sth->execute() or die "Unable to execute".$sth->errstr;

的錯誤消息是Unable to execute at D:\Demo\perl_demo\subject.pl line 24.

得到錯誤但當我打印$胸徑變量,它給像DBI::db=HASH(0x1ca7884)結果。所以我猜連接正在建立。

請幫我解決這個問題,因爲我是全新的Perl腳本。

+1

你檢查的$ dbh-的返回值>準備($ SQL)? –

+0

你肯定有連接,否則它會死在連接('connect ..或die ..') –

+0

是的弗蘭克,我已經檢查$ dbh-> prepare($ sql)的返回值。它給'DBI :: db = HASH(0x1ca74f4)' –

回答

1

檢查上prepare錯誤,

my $sth = $dbh->prepare($sql) or die $dbh->errstr; 
+0

我已經檢查了點你的代碼。但它沒有拋出任何錯誤。當我打印$ sth變量時,它的結果如'DBI :: db = HASH(0x1ca74f4)' –

+0

@KanhuCharanSahu奇怪的是'$ sth-> execute()或者$ sth-> errstr;'不會報告實際的錯誤消息? –

+0

是由於遠程數據庫? –