无法通过包“DBI :: db”找到对象方法“execute”

时间:2012-08-09 15:18:07

标签: perl dbi

我的代码如下:

sub new {
    my $class = shift;
    my $self = bless {}, $class;

    $self->initialize();

    return $self;
}

sub initialize
{
    my $self = shift;

    $self->connect();

    $self->{'dbh'}
        ->do("CREATE TABLE IF NOT EXISTS 'settings' (Id INTEGER PRIMARY KEY, Option TEXT, Value TEXT)");
}

sub connect
{
    my $self = shift;

    $self->{'dbh'} = DBI->connect($self->DSN, "", "", {
        RaiseError => 1,
        AutoCommit => 1
    });

    die "Can't connect" unless($self->{'dbh'});
}

sub no_options
{
    my$self = shift;

    $self->{'dbh'}->prepare("SELECT COUNT(*) as Total FROM settings");
    # Here is the problem i get the error here:
    # Can't locate object method "execute" via package "DBI::db"
    $self->{'dbh'}->execute();
    my %row = $self->{'dbh'}->fetchhash_array;

    return $row{'Total'};
}

在其他地方,我打电话给我的包

my $test = Lib::PackageName->new;

print $test->no_options;

2 个答案:

答案 0 :(得分:5)

prepare方法返回一个语句对象。这个对象具有execute方法。

my $statement = $self->{'dbh'}->prepare("SELECT COUNT(*) as Total FROM settings");
$statement->execute();

DBI中没有名为fetchhash_array的方法。语句对象的可用提取方法是:

答案 1 :(得分:1)

$self->{'dbh'}->prepare(...)返回一个语句句柄,您应该保留以供进一步使用:

my $sth = $self->{'dbh'}->prepare("SELECT COUNT(*) as Total FROM settings");
$sth->execute;
my %row = $sth->fetchhash_array;
相关问题