2013-04-02 97 views
0

每當我嘗試使用此方法時,都會收到此問題。java.sql.SQLException:在ResultSet關閉後不允許執行操作MySQL Java

java.sql.SQLException: Operation not allowed after ResultSet closed 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926) 
    at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794) 
    at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7077) 
    at server.util.Plimus$1.run(Plimus.java:77) 

這是關於線77:while (resultSet.next()) {

public static void process(final Player c, final String playerName) { 
    if (connection == null && connectionStatus == 0) 
     createConnection(); 
    else if (connectionStatus != 0) 
     return; 
    new Thread() { 
     @Override 
     public void run() { 
      try { 
       String username = playerName.replaceAll(" ", "_"); 
       String query = "SELECT * FROM donations WHERE username = '" + username + "' AND received = '0' LIMIT 1;"; 
       ResultSet resultSet = query(query); 
       while (resultSet.next()) { 
        int[] contractIds = {3178768, 1}; //put all of your contract ids in here. 
        int contractId = Integer.parseInt(resultSet.getString("contract")), id = Integer.parseInt(resultSet.getString("id")); 
        query("UPDATE donations SET received = '1' WHERE username = '" + username + "' AND id = '" + id + "';"); 
        if (contractId == contractIds[0]) { //first contract id in array. 
         c.getItems().addItem(962, 1); 
        } else if (contractId == contractIds[1]) { //second contract id in array. 
         c.getItems().addItem(962, 1); 
        } 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
       processMethod(0, true, true, false); 
      } 
     } 
    }.start(); 
} 

這裏是所請求的查詢方法。

/** 
* Creates query function. 
*/ 
public static ResultSet query(String s) throws SQLException { 
    try { 
     if (s.toLowerCase().startsWith("select")) { 
      ResultSet resultSet = statement.executeQuery(s); 
      return resultSet; 
     } else { 
      statement.executeUpdate(s); 
     } 
     return null; 
    } catch (Exception e) { 
     e.printStackTrace(); 
     processMethod(0, true, true, false); 
    } 
    return null; 
} 
+2

在哪一行你會得到這個異常? – bsiamionau

+0

也發帖查詢方法 –

+0

查詢方法做什麼? – Jakob

回答

2

在遍歷你ResultSet,正在重用的Statement對象更新,其中關閉從查詢ResultSet(你query方法內部)的數據。

ResultSet documentation

「當生成它的Statement對象被關閉時,重新執行,或用於檢索從多個結果的序列中的下一個結果一個結果對象被自動關閉」

您應該創建查詢和更新單獨的語句,並傳遞給你的查詢方法:

public ResultSet query(String s, Statement statement) throws SQLException { 
    ... 
} 

我認爲statement聲明static你的類中 - 通常沒有必要那就是:在你的類的構造函數中創建兩個用於查詢和更新的語句,並將它們傳遞給query()方法或根據語句使用其中一個或另一個。

相關問題