2012-08-15 51 views
0

我試圖改善其選擇從HSQLDB數據的功能,所以我試圖在多個線程中運行它,但我得到了以下異常:的executeQuery在多線程關閉HSQLDB數據庫連接

java.sql.SQLNonTransientConnectionException: connection exception: closed 
    at org.hsqldb.jdbc.Util.sqlException(Unknown Source) 
    at org.hsqldb.jdbc.Util.sqlException(Unknown Source) 
    at org.hsqldb.jdbc.Util.sqlException(Unknown Source) 
    at org.hsqldb.jdbc.JDBCStatementBase.checkClosed(Unknown Source) 
    at org.hsqldb.jdbc.JDBCStatementBase.getResultSet(Unknown Source) 
    at org.hsqldb.jdbc.JDBCStatement.getResultSet(Unknown Source) 
    at org.hsqldb.jdbc.JDBCStatement.executeQuery(Unknown Source) 

這是函數我試圖每次都在一個新的線程運行它:

public List<String> getAllClassNames(boolean concrete) throws ClassMapException { 
     List<String> result = new ArrayList<String>(); 


     try { 
      ResultSet rs = null; 
      Connection connection = DBConnection.getConnection(); 
      Statement st = connection.createStatement(); 
      if (concrete) 
       rs = st.executeQuery("select cd_name from CLASS_DESCRIPTORS where CD_CONCRETE=true order by cd_name"); 
      else 
       rs = st.executeQuery("select cd_name from CLASS_DESCRIPTORS order by cd_name"); 
      while (rs.next()) { 
       result.add(rs.getString("cd_name")); 
      } 
     } catch (SQLException e) { 
      _log.error("SQLException while retrieve all class names." + e.getMessage(), e); 
      throw new ClassMapException("SQLException while retrieve all class names." + e.getMessage(), e); 
     } finally { 
      DBConnection.closeConnection(); 
     } 
     return result; 
    } 

我讀到執行多個選擇由不同的線程關閉連接。這是真的嗎?如何解決?

回答

1

看起來連接已關閉,因爲該功能使用了相同的連接,並在首次使用後關閉。檢查你的DBConnection類是如何寫入的。

代碼中還有其他問題,例如st語句從不關閉,或者語句沒有準備好然後重用。

您還可以使用HSQLDB中的ARRAY_AGG函數返回您的數組,而不是自己創建它。鏈接到指南和使用示例如下。

http://hsqldb.org/doc/2.0/guide/dataaccess-chapt.html#N12538

select array_agg(cd_name order by cd_name) as arr from CLASS_DESCRIPTORS where CD_CONCRETE=true 

Array array = rs.getArray(1) 

該陣列是JDBC陣列,並且可以通過它的JDBC方法來引用。

+0

我該如何使用ARRAY_AGG?你能修改我的查詢來使用它嗎? – 2012-08-15 12:19:10

+1

更新了答案。 – fredt 2012-08-15 15:41:44

+0

我試過你的解決方案,但是當我執行rs.getArray(1)時,我得到了「無效遊標狀態:標識符遊標未定位在UPDATE,DELETE,SET或GET語句中的行上;; ResultSet定位在第一行之前」異常。你有什麼想法如何解決它? – 2012-08-16 09:14:10