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