user2932003
user2932003

Reputation: 181

Can't locate object method "prepare" via package "DB_CONNECT"

I have create package to make a connection with database the code is given below:

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

Here a set of Perl code to fetch the data from database.

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

whenever I'm executing my Perl Program i'm getting following error :

Can't locate object method "prepare" via package "DB_CONNECT"

Upvotes: 0

Views: 3044

Answers (2)

AKHolland
AKHolland

Reputation: 4445

It looks like you want to dispatch prepare into db->{'_dbh'}. You can do this either by calling it explicitly like $db->{'_dbh'}->prepare($sql), or by using autoload like:

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";
}

Which will make it possible to call $db->prepare($sql) and have the method call dispatched to $db->{'_dbh'}.

However it might be better to accomplish whatever you're trying to do by subclassing DBI. There is good documentation for this on CPAN.

Upvotes: 1

blio
blio

Reputation: 483

well, you define a database connector by yourself in the DB_CONNECT.pm, however, in the file, there is no method named by prepare. Your self-defined object is different from the standard of dbi method. So in this way, you have to implement it the method by yourself or you can use the standard DBI. What you need is here http://metacpan.org/pod/DBI#prepare

Upvotes: 0

Related Questions