Perl dbi 断开连接时重新连接
我搜索过谷歌,但找不到我认为简单问题的答案。
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DBD::mysql 驱动程序(DBI 用于 MySQL 数据库) ) 支持属性
mysql_auto_reconnect
。要打开它,只需执行请注意,文档有此警告:
The DBD::mysql driver (that DBI uses for MySQL databases) supports an attribute
mysql_auto_reconnect
. To turn it on, just executeNote that the docs have this warning:
您还可以查看此线程: 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.