This error occurs because the MySQL server closes the connection, if the client program performs any database operations within the default 8 hours. Solution:
1. modify my. CNF: You can change wait_timeout and interactive_timeout to set an extended timeout period. However, we do not recommend this operation. This operation will lead to many database connections and affect the database performance;
The setting method is as follows:
[Mysqld]
Wait_timeout = 5
Interactive_timeout = 5
Two variables must be set at the same time;
2. Set Database options to reconnect when the connection is disconnected.
Char nvalue = 1;
If (mysql_options (& MySQL, mysql_opt_reconnect, (char *) & nvalue ))
Printf ("mysql_options/R/N ");
3. Ping the database before performing the database operation. If the database cannot be connected, disconnect and restart the database.
If (mysql_ping (sqlsock )! = 0) {// reconnect failed... then try connect
Closedb ();
If (sqlsock = mysql_real_connect (& MySQL, dbhost, dbuser, dbpassword, dbname, 0, null, client_interactive) = NULL)
{
Fprintf (stderr, "can't connect to MySQL sever! Errorcode: % S/R/N ", mysql_error (& MySQL ));
Return-1;
}
Printf ("connectdb/R/N ");
}
For the sake of insurance, I use the restart connection to close the connection;
For this method, I suggest using a thread to ping at a certain time. If the ping fails, the connection operation will be performed again.
4. Similar to the first method, the timeout time is also set, but this timeout time is only valid for this connection;
Mysql_options (& MySQL, mysql_init_command, "set interactive_timeout = 15 ");
Mysql_options (& MySQL, mysql_init_command, "set wait_timeout = 15 ");
Note: When the connection between the client and the server is disconnected (for example, the network cable is unplugged), the connection still exists after the network recovers. This is the function of the TCP retransmission mechanism, TCP retransmission time. The local test lasts for more than 10 minutes, and it is still normal after recovery.
1) No parameter set for TCP retransmission time is found. You can follow the instructions;
2) I have not found a good way to manually disconnect the database. I may test it later if the network is disconnected for a long time, how to restore the database connection (try to ping the database ).