No operations allowed after statement closed.

之因此會出現這個異常,是由於Mysql在5之後針對超長時間DB鏈接作了一個處理,那就是若是一個DB鏈接在無任何操做狀況下過了8個小時後,Mysql會自動把這個鏈接關閉。因此使用鏈接池的時候雖然鏈接對象還在可是連接數據庫的時候會一直報這個異常。解決方法很簡單在Mysql的官方網站上就能夠找到。 有兩個方法
###第一種是在DB鏈接字符串後面加一個參數。
這樣的話,若是當前連接由於超時斷掉了,那麼驅動程序會自動從新鏈接數據庫。java

jdbc:mysql://localhost:3306/makhtutat?autoReconnect=true

不過Mysql並不建議使用這個方法。由於第一個DB操做失敗的後,第二DB成功前若是出現了從新鏈接的效果。mysql

conn.createStatement().execute(
  "UPDATE checking_account SET balance = balance - 1000.00 WHERE customer='Smith'");
conn.createStatement().execute(
  "UPDATE savings_account SET balance = balance + 1000.00 WHERE customer='Smith'");
conn.commit();

固然若是出現了從新鏈接,一些用戶變量和臨時表的信息也會丟失。 ###另外一種方法是Mysql推薦的,須要程序員手動處理異常。程序員

Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    int retryCount = 5;
    boolean transactionCompleted = false;
    do {
        try {
            conn = getConnection(); // assume getting this from a
                                    // javax.sql.DataSource, or the
                                    // java.sql.DriverManager
            conn.setAutoCommit(false);
            retryCount = 0;
            stmt = conn.createStatement();
            String query = "SELECT foo FROM bar ORDER BY baz";
            rs = stmt.executeQuery(query);
            while (rs.next()) {
            }
            all.close()
            transactionCompleted = true;
        } catch (SQLException sqlEx) {
            String sqlState = sqlEx.getSQLState();
           // 這個08S01就是這個異常的sql狀態。單獨處理手動從新連接就能夠了。
            if ("08S01".equals(sqlState) || "40001".equals(sqlState)) 
                {                
                    retryCount--;            
                 } else {                
                     retryCount = 0;            
                     }        
         } finally {            
                 all close:        
             }    
      } while (!transactionCompleted && (retryCount > 0));}
}
相關文章
相關標籤/搜索