Mysql

关注公众号 jb51net

关闭
首页 > 数据库 > Mysql > Mysql的timeout及python重连

Mysql的timeout以及python重连方式

作者:有人找你

这篇文章主要介绍了Mysql的timeout以及python重连方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

 问题

近期使用多线程对数据库操作报错:

(2013, 'Lost connection to MySQL server during query')

 解决方案

1. 更改timeout参数

出现这个问题顺便就了解了一下mysql中的timeout都有什么:

mysql> show variables like '%timeout%';
+-----------------------------+----------+
| Variable_name               | Value    |
+-----------------------------+----------+
| connect_timeout             | 10       |
| delayed_insert_timeout      | 300      |
| have_statement_timeout      | YES      |
| innodb_flush_log_at_timeout | 1        |
| innodb_lock_wait_timeout    | 50       |
| innodb_rollback_on_timeout  | OFF      |
| interactive_timeout         | 28800    |
| lock_wait_timeout           | 31536000 |
| net_read_timeout            | 30       |
| net_write_timeout           | 60       |
| rpl_stop_slave_timeout      | 31536000 |
| slave_net_timeout           | 60       |
| wait_timeout                | 28800    |
+-----------------------------+----------+
13 rows in set (0.06 sec)

很多参数,网上对于connection lost这个问题有说改wait_timout也有说net_read_timeout和net_write_timeout的。

那么他们之间到底有什么区别呢?

简单来说:

This for example typical cause of aborted connections while using Sphinx with large data sets and large buffers. While indexing Sphinx performs sorts and flushes buffers to the disk every so often which can take long enough to trigger default net_write_timeout on the server side.

You could ask why server does not do any flow control and can’t find out client just is just busy and it is not network issue – well this comes from simplicity of MySQL protocol which does not allow client to talk to the server until full result set is fetched. This is also the reason why you can’t stop fetching for ordinary statements and mysql_free_result will have to complete the fetch internally.

Is there any way to tell the server you need more time besides increasing net_write_timeout ? Not what I know of. You can’t use something like mysql_ping because connection is in the stage of getting the data. You can’t even fetch couple of rows every few seconds to show you’re fetching data because there is buffering happening inside MySQL client library so you never know when real network read will happen.

具体改什么还要视自己的情况而定:

详细的net write timeout和wait timeout的比较

2. 测试连接,并将断开的连接重新连接

还有另一个办法,python使用ping()方法测试连接。

但是要注意ping方法不能在使用流式游标进行迭代获取数据的过程中用,

否则会报错:

UserWarning: Previous unbuffered result was left incomplete warnings.warn("Previous unbuffered result was left incomplete")

ping()应用于两个sql语句执行之间进行查询,

这个检查是为了应付由于超出wait_timeout(而非net_read/write_timeout)服务器自动断开链接的。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文