Perl dbi 断开连接时重新连接

发布于 2024-12-16 10:40:54 字数 634 浏览 0 评论 0原文

我搜索过谷歌,但找不到我认为简单问题的答案。

我有一个 Perl 代码(下面的示例),每 3 秒获取一次数据,并将接收到的数据更新到 MySQL 数据库中,但有时 MySQL 数据库不可用,脚本会死掉。如果MySQL连接失败,如何重新连接?

use DBD::Mysql;

sub updateMysqlDB{
my $connect = DBI->connect("dbi:mysql:$database:$host", 
                        $user,
                        $pw,
                        {RaiseError => 1}
                        );
$myquery = "My sql query to insrt data into columns";
$query_handle=$connect->prepare($myquery);
$query_handle->execute();
$connect->disconnect;
}

while (1) {

if data received call updateMysqlDB ();

else wait for data { sleep 3 ;}
}

I have searched google but could not find an answer to what I think is an easy question.

I have a Perl code (example below) that gets data every 3 seconds and updates the received data into MySQL database but sometimes MySQL database is not available and the script dies. How can I make MySQL connection again if it fails?

use DBD::Mysql;

sub updateMysqlDB{
my $connect = DBI->connect("dbi:mysql:$database:$host", 
                        $user,
                        $pw,
                        {RaiseError => 1}
                        );
$myquery = "My sql query to insrt data into columns";
$query_handle=$connect->prepare($myquery);
$query_handle->execute();
$connect->disconnect;
}

while (1) {

if data received call updateMysqlDB ();

else wait for data { sleep 3 ;}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

像你 2024-12-23 10:40:54

DBD::mysql 驱动程序(DBI 用于 MySQL 数据库) ) 支持属性 mysql_auto_reconnect。要打开它,只需执行

$connect->{mysql_auto_reconnect} = 1;

请注意,文档有此警告:

如果使用“锁表”,则不建议将 mysql_auto_reconnect 设置为 on,因为如果 DBD::mysql 重新连接到 mysql,所有表锁都将丢失。当 AutoCommit 关闭时该属性被忽略,并且当 AutoCommit 关闭时,DBD::mysql 不会自动重新连接到服务器。

The DBD::mysql driver (that DBI uses for MySQL databases) supports an attribute mysql_auto_reconnect. To turn it on, just execute

$connect->{mysql_auto_reconnect} = 1;

Note that the docs have this warning:

Setting mysql_auto_reconnect to on is not advised if 'lock tables' is used because if DBD::mysql reconnect to mysql all table locks will be lost. This attribute is ignored when AutoCommit is turned off, and when AutoCommit is turned off, DBD::mysql will not automatically reconnect to the server.

蘸点软妹酱 2024-12-23 10:40:54

您还可以查看此线程: http://www.perlmonks.org/?node_id=317168

这讨论了处理“MySQL 服务器已消失”问题的方法,但一些答案也适用于您的问题。除了 mysql_auto_reconnect 开关之外,您还可以使用那里的建议。

You can also look at this thread : http://www.perlmonks.org/?node_id=317168

This discusses the way to deal with "MySQL server has gone away" problem, but a few answers apply to your problem too. You can use the recommendations there, in addition to the mysql_auto_reconnect switch.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文