2

我的代码如下:

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;
4

2 回答 2

5

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

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

fetchhash_array中没有命名方法DBI。语句对象的可用获取方法有:

于 2012-08-09T15:22:54.740 回答
1

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

my $sth = $self->{'dbh'}->prepare("SELECT COUNT(*) as Total FROM settings");
$sth->execute;
my %row = $sth->fetchhash_array;
于 2012-08-09T15:26:10.717 回答