首页 > 开发 > MySQL > 正文

在设置了MYSQL_OPT_RECONNECT之后,mysql_ping是否还有必要?

2017-09-08 09:11:40  来源:网友分享

根据官方文档

Checks whether the connection to the server is working. If the connection has gone down and auto-reconnect is enabled an attempt to reconnect is made. If the connection is down and auto-reconnect is disabled, mysql_ping() returns an error.

也就是说,如果 MYSQL_OPT_RECONNECT 没有被设置为 1(开启),那么mysql_ping()不会完成自动重连,只是简单返回一个error。

那么如果已经开启这个选项了呢?官方文档又说了

MYSQL_OPT_RECONNECT (argument type: my_bool *)
Enable or disable automatic reconnection to the server if the connection is found to have been lost.

也就是说,如果发现连接断开,那么会启动自动重连功能。

现在问题是:连接断开这事儿是啥时候被发现的呢?

根据官方文档mysql_ping()肯定是会发现,那mysql_query()是否会"发现"呢?

解决方案

写代码测试 + 追了一下MySQL的源码,结论是mysql_query()会"发现"。只要直接或间接调用了MySQL源码中 cli_advanced_command() 的函数,都会"发现"。

由于整个过程挺复杂的,详情就不列出来了,有兴趣的同学可以参考我的这篇博客