无法在未定义的值上调用方法“execute”

时间:2013-07-27 10:22:34

标签: perl dbi

每当我执行下面的程序时,我都会从以下行收到错误消息Can't call method "execute" on an undefined value

$sth->execute($agent_name,$service_id,$call_start_time,$call_end_time);

但是在同一个程序中,我能够执行下面评论中指出的第一个SQL查询:

#!/usr/bin/perl -w
use strict;
use DBI;

my $DSN = q/dbi:ODBC:SQLSERVER/;
my $uid = q/ivr/;
my $pwd = q/ivr/;
my $DRIVER = "Freetds";
my $dbh = DBI->connect($DSN,$uid,$pwd) or die "Coudn't Connect SQL";
my $servernumber = 2;

my $service_name = "JM";
my $agent_name= 'Balaji';
my $call_start_time='2013-07-01 15:46:50.865';
my $call_end_time='2013-07-15 15:46:50.789';
my $call_rec_file_name;

my $rows_fund = $dbh->selectrow_array("select count(service_name) from cti_services  where service_name='$service_name'");
my $rows_agent = $dbh->selectrow_array("select count(agent_name) from cti_agents where agent_name='$agent_name'");

# This query successfully executes:
my $sql_fund = "select service_id from cti_services where service_name='$service_name'";
my $sth_fund = $dbh->prepare($sql_fund);
$sth_fund->execute() or die $DBI::errstr;
my $service_id = $sth_fund->fetchrow();
print $service_id,"\n";

if( $rows_fund == 1 && $rows_agent == 1 )
{
    my $sql="select top(10) service_name,agent_name,call_rec_file_name,call_start_time,call_end_time from cti_agents join  cti_call_master on (agent_name = call_agent_name) join cti_services on (call_service_id = service_id) where agent_name = ? and call_rec_file_name is not null and service_id=? and call_start_time between ? and ?";

    my $sth = $dbh->prepare($sql);

    # The problem is with this query. I'm getting the error "Can't call method "execute" on an undefined value".
    $sth->execute($agent_name,$service_id,$call_start_time,$call_end_time);

    print "Service Name","Agent Name","Call Start Time ","Call End Time","Sound File " ;
    while (my @data = $sth->fetchrow_array())
    {
        my ($service_name,$agent_name,$call_rec_file_name,$call_start_time,$call_end_time ) = @data;
        print "$service_name","$agent_name ","$call_start_time ","$call_end_time ","  $call_rec_file_name ";
    }
}
else
{
    print "<em>","There is no data found","</em>";
}

$dbh->disconnect;

可能导致错误消息的原因是什么?

3 个答案:

答案 0 :(得分:3)

$sth未定义,因为您对$dbh->prepare的调用因某种原因失败。

如果您使用以下内容替换您的DBI-&gt; connect()调用,您将从prepare调用中收到错误,而不是在您尝试调用{{1}时无声地失败并进行轰炸}:

execute

您可以在此处阅读有关RaiseError以及DBI调用可用的其他属性的更多信息:https://metacpan.org/module/DBI#RaiseError

我必须承认我无法立即看到错误,我的预感是SQL语法问题,但我不会说SQLServer。

答案 1 :(得分:1)

if内的前两行更改为此

my $sth = $dbh->prepare(<<__SQL__) or die $dbh->errstr;
SELECT TOP(10) service_name, agent_name, call_rec_file_name, call_start_time, call_end_time
FROM cti_agents
JOIN cti_call_master ON (agent_name = call_agent_name)
JOIN cti_services ON (call_service_id = service_id)
WHERE agent_name = ?
AND call_rec_file_name IS NOT NULL
AND service_id = ?
AND call_start_time BETWEEN ? AND ?
__SQL__

然后你会看到错误的原因。

请注意__SQL__之前或之后必须没有空格

答案 2 :(得分:0)

在sql中输入引号作为日期时间,它可能在解析期间看到空格?