Recently done a project daemon, need to multi-threading MySQL database service operation, in order to strengthen the robustness of the Guardian support, the connection was successful after unplugging the network cable, and then test the daemon to disconnect the robustness of the reconnect, but found that the network is disconnected, re-plug the cable, with Mysql_real_ Conncet The reconnection returned is always false, that is, reconnection fails, after I want to disconnect the MySQL connection after disconnecting (Mysql_close (MySQL)) , and Reinitialize Mysql_init ((MySQL )), Then use the Mysql_real_conncet () function to connect, but the consequences of this is Mysql_real_connect () error, error content for not enough memory, obviously my computer also has 5 g free memory, actually said memory is not enough ...
After consulting the data, found that there is a function called mysql_options, combined with the mysql_ping function, MySQL connection can be automatically reconnected after disconnecting:
Use mysql_ping to check for re-connection. Use two functions, one is mysql_ping, the other is mysql_options. The specific use is to use mysql_options before Mysql_real_connect, after Mysql_init. Use the following:
char Value = 1 ; (void ) Mysql_init (&mysql); Mysql_options (&mysql, Mysql_opt_reconnect, (char *) & value );
How to use Baidu Encyclopedia:
Mysql_optins
Mysql_ping
Then, before mysql_query, first use mysql_ping to determine if the connection has been disconnected, will automatically reconnect, or after the query fails, execute the mysql_ping function, and then automatically re-connect Mysqlsever.
However, please note that Automatic reconnection can also cause some side effects, as follows:
* Any active transactions are rolled back and autocommit mode is reset.
* All table locks are released
* All temporary tables are off (undo)
* Session variables is reinitialized to the values of the corresponding variables. The conversation variable is reinitialized to the appropriate variable. This also affects those implicitly declared variables, SET NAMES. For example, use this also affects variables, which is set implicitly by statements such as set NAMES. It also affects the variable, which is set by the implicit declaration, such as the name of the setting.
* User variable settings will be lost.
* Prepare report release.
* Handle variable is closed.
* LAST_INSERT_ID () is reset to 0.
* Locks obtained using Get_lock () are released
MySQL Network disconnect re-connect issue