Perl DBI来自不同对象的一个​​连接:问题

时间:2013-11-03 17:06:06

标签: sql perl connect dbi

在我的脚本中,创建了几个使用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

1 个答案:

答案 0 :(得分:0)

我找到了问题的答案!

主DBI-class有析构函数:

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

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