Mysql連線超時解決辦法(mysql-jdbc)
阿新 • • 發佈:2019-02-04
mysql的超時後,其實不用修改mysql的配置。那樣做其實會使mysql存在很大的安全問題。
mysql-jdbc有個很好的解決辦法,如果出現連線超時,可以判斷後自動重連
/** * 判斷連線是否有效 * @param conn * @return boolean */ private boolean checkConnection(Connection conn) { try { if(conn instanceof com.mysql.jdbc.Connection) { ((Connection)conn).ping();//ping通mysql方法,如果超時會拋異常 } Statement pingStatement = null; try { pingStatement = (Statement) conn.createStatement(); pingStatement.executeQuery("SELECT 1").close();//測試是否超時的另一種做法 } finally { if (pingStatement != null) { pingStatement.close(); } } return CONNECTION_IS_OKAY; //自定義值 } catch (SQLException e) { // TODO Auto-generated catch block return CONNECTION_IS_INVALID; //自定義值 } }