【发布时间】:2012-08-26 04:00:45
【问题描述】:
我有一个在 while 循环中永远运行的守护程序脚本。我有一个准备好的语句,这个语句在每个循环中执行。
例子:
my $dbh;
sub get_dbh {
return DBI->connect(...);
}
my $dbh = get_dbh();
my $sth = $dbh->prepare("SELECT ....") or die $DBI::errstr;
while (1) {
// is connection still there??
//if (!$dbh->ping) {
// $dbh = get_dbh();
//}
$sth->execute('param1');
// do some other things ... sleep between 0 and 3600
}
如果准备好的语句在几个小时前准备好,就会出现(或可能出现)问题。连接可能会死,我也会执行。在每次执行之前检查 $dbh->ping 看起来有点过头了。
MySQL 支持真正有效的 mysql_auto_reconnect。 DBD::Pg 没有这样的东西。我读过 DBI::Apache 但我看到它依赖于 mod_perl 等。它显然适用于 Web 应用程序。
是否有“最佳实践”方法来检查连接状态并在需要时重新连接?#
我可以在每个循环上准备语句,但这不是解决方案,而是解决问题的一种方法。
【问题讨论】:
-
我决定将您的答案与 connect_cached 和 prepare_cached 结合使用。
标签: perl postgresql connection reconnect dbd-pg