之所以会出现这个异常,是因为Mysql在5以后针对超长时间DB连接做了一个处理,那就是如果一个DB连接在无任何操作情况下过了8个小时后,Mysql会自动把这个连接关闭。所以使用连接池的时候虽然连接对象还在但是链接数据库的时候会一直报这个异常。解决方法很简单在Mysql的官方网站上就可以找到。 有两个方法
###第一种是在DB连接字符串后面加一个参数。
这样的话,如果当前链接因为超时断掉了,那么驱动程序会自动重新连接数据库。
jdbc:mysql://localhost:3306/makhtutat?autoReconnect=true
不过Mysql并不建议使用这个方法。因为第一个DB操作失败的后,第二DB成功前如果出现了重新连接的效果。
1conn.createStatement().execute( 2 "UPDATE checking_account SET balance = balance - 1000.00 WHERE customer='Smith'"); 3conn.createStatement().execute( 4 "UPDATE savings_account SET balance = balance + 1000.00 WHERE customer='Smith'"); 5conn.commit();
当然如果出现了重新连接,一些用户变量和临时表的信息也会丢失。 ###另一种方法是Mysql推荐的,需要程序员手动处理异常。
1 Connection conn = null; 2 Statement stmt = null; 3 ResultSet rs = null; 4 int retryCount = 5; 5 boolean transactionCompleted = false; 6 do { 7 try { 8 conn = getConnection(); // assume getting this from a 9 // javax.sql.DataSource, or the 10 // java.sql.DriverManager 11 conn.setAutoCommit(false); 12 retryCount = 0; 13 stmt = conn.createStatement(); 14 String query = "SELECT foo FROM bar ORDER BY baz"; 15 rs = stmt.executeQuery(query); 16 while (rs.next()) { 17 } 18 all.close() 19 transactionCompleted = true; 20 } catch (SQLException sqlEx) { 21 String sqlState = sqlEx.getSQLState(); 22 // 这个08S01就是这个异常的sql状态。单独处理手动重新链接就可以了。 23 if ("08S01".equals(sqlState) || "40001".equals(sqlState)) 24 { 25 retryCount--; 26 } else { 27 retryCount = 0; 28 } 29 } finally { 30 all close: 31 } 32 } while (!transactionCompleted && (retryCount > 0));} 33}