0

在我的脚本中创建了几个使用 DBI 包装器的不同对象:

package MY::DB;
use DBI;

sub my_connect {
  my ($class, %p) = @_;
  my $dbh = DBI->connect(...);
  $dbh->do("SET NAMES cp1251");
  return bless {dbh => $dbh}, $class;
}

sub query {
  my ($self, $sql) = @_;
  # sql execution
}
...

我决定只使用一个到数据库的连接来优化脚本。尝试了两个选项:全局变量和 DBI->connect_cached(..) 方法。结果是一样的:连接实际上是对所有对象使用一个,但是连接后不处理sql代码:

...
sub my_connect {
  my ($class, %p) = @_;
  my $dbh = DBI->connect_cached(...);
  $dbh->do("SET NAMES cp1251"); # no effect :(
  return bless {dbh => $dbh}, $class;
}
...

例如我有课:

package MY::USER;
use base 'MY::DB';
sub constructor {
    my ($class) = @_;
    return MY::DB::my_connect($class);
}
sub get_info_1 {
  my ($self) = @_;
  $self->query(...);
}
sub get_info_2 {
  my ($self) = @_;
  $self->query();
}

package MY::NEWS;
use base 'MY::DB';
sub constructor {
    my ($class) = @_;
    return MY::DB::my_connect($class);
}
sub get_info {
  my ($self) = @_;
  $self->query(...);
}

脚本:

use MY::USER;
use MY::NEWS;

my $user = MY::USER->constructor;
my $news = MY::NEWS->constructor;

$user->get_info_1; # OK
$news->get_info; # OK
$user->get_info_2; # here $dbh->do("set names cp1251") operation no effect
4

1 回答 1

0

我找到了我的问题的答案!

主要 DBI 类具有析构函数:

sub DESTROY {
    my ($self) = @_;
    $self->{dbh}->disconnect;
}

这个班的所有孩子都有它。在 NEWS->get_info() 内部调用并销毁了相同的对象,并断开了与数据库的链接……但定义了 DBH 变量的值!

于 2013-11-08T21:22:40.583 回答