无法通过包"DB_CONNECT"找到对象方法"prepare"



我创建了包来与数据库建立连接,代码如下:

#!/usr/bin/perl
#Class
package DB_CONNECT;
#Constructor
        sub new {
                        my ($class)=@_;
                        my $self={};
                        $self->{_odbc}="dbi:ODBC:SQLSERVER";
                        $self->{_username}="xxx";
                        $self->{_password}="xxx";
                        $self->{_dbh}=my $dbh;
                        bless $self, $class;
                        return $self;
                }
###Method to open the database connection
        sub db_connect
                {
                use DBI;
                my ($self)=@_;
                $self->{_dbh}=DBI->connect($self->{_odbc},$self->{_username},$self->{_password},{PrintError => 1}) || die "Database connection not made: $DBI::errstr";
                return 1;
                }
1;

这里有一组Perl代码,用于从数据库中获取数据。

#!/usr/bin/perl
#use strict;
use Data::Dumper;
use Asterisk::AGI;
use DB_CONNECT;
#require("/root/DB_CONNECT.pm");
my $agi = new Asterisk::AGI;
my $db = DB_CONNECT->new();
my $sql = "EXEC usp_sms_ticket '".$status_data."'";
my $sth = $db->prepare($sql);
$sth->execute();
$return = $sth->fetchrow();
$agi->set_variable('result',$return);
print Dumper($return);
$sth->finish;
$db->disconnect;

每当我执行Perl程序时,我都会收到以下错误:

无法通过包"DB_CONNECT"找到对象方法"准备"

看起来您想将prepare分派到db->{'_dbh'} 中。您可以通过像 $db->{'_dbh'}->prepare($sql) 一样显式调用它或使用自动加载来执行此操作,例如:

use AutoLoader 'AUTOLOAD';
sub AUTOLOAD {
    my $self = shift;
    (my $method = $AUTOLOAD) =~ s/.*:://;
    if($self->{'_dbh'}->can($method)) {
        return $self->{'_dbh'}->$method(@_);
    }
    die "Unknown method '$method'n";
}

这将使调用$db->prepare($sql)并将方法调用调度到$db->{'_dbh'}成为可能。

但是,最好通过子类化 DBI 来完成您尝试执行的任何操作。CPAN 上有很好的文档。

好吧,您可以在 DB_CONNECT.pm 中自己定义数据库连接器,但是,在文件中,没有由 prepare 命名的方法。您的自定义对象与 dbi 方法的标准不同。所以这样,你必须自己实现它的方法,或者你可以使用标准的DBI。您需要的就在这里http://metacpan.org/pod/DBI#prepare

最新更新