2011-12-12 4 views
0

내 데이터베이스에 uid1 - 누군가의 ID, uid2 - 그의 친구가있는 테이블이 있습니다.Java ResultSet with postgresql

나는 누군가의 친구가있는 곳에서 5 깊이 연결까지 목록을 만들고 싶습니다.

그래서 나는 다음과 같은 재귀 방법 내장 :

private void recursive(int theUid,ResultSet rs,ArrayList<Integer> friends,int count,int next,PreparedStatement pstmt) throws SQLException{ 
     if(count>=1 && next==theUid){ 
      return; 
     } 
     else if(count>=DEPTH_OF_CONNECTION){ 
      return; 
     } 

     else{ 
      pstmt.setInt(1,next); 
      rs=pstmt.executeQuery(); 
      count++; 
      while(rs.next()) { 
       friends.add(rs.getInt(1)); 
       recursive(theUid,rs,friends,count,rs.getInt(1),pstmt); 
      } 
     } 
    } 
} 

을 그리고 나는 다음과 같은 오류 있어요 :

Exception in thread "main" org.postgresql.util.PSQLException: This ResultSet is closed. at org.postgresql.jdbc2.AbstractJdbc2ResultSet.checkClosed(AbstractJdbc2ResultSet.java:2654) at org.postgresql.jdbc2.AbstractJdbc2ResultSet.next(AbstractJdbc2ResultSet.java:1786)

당신이 날 문제가 무엇을 찾을 수 있습니까?

+0

을 당신은 당신이 PostgreSQL을 단지 하나의 문으로 할 수있는 알고

Postgres jdbc driver doc 그것을 확인하는 것? –

+0

매 단계마다 서버와 대화하는 것은 매우 비쌉니다. [재귀 CTE] (http://www.postgresql.org/docs/9.1/static/queries-with.html)를 사용하는 단일 쿼리가 최선의 방법입니다. –

답변

9

Javadoc

By default, only one ResultSet object per Statement object can be open at the same time.

그래서 내 생각 엔 당신이 동일한 시간에 동일한 PreparedStatement의 너무 많은 결과 집합을 열려고 말합니다.

편집 :

You can use a single Statement instance as many times as you want. You could create one as soon as you open the connection and use it for the connection's lifetime. But you have to remember that only one ResultSet can exist per Statement or PreparedStatement at a given time.

+1

당신의 [right] 대답을 완성하기 만하면됩니다. 코드는 모든 친구를 결과 집합에서 가져 와서 닫은 다음 목록에서 반복합니다. – jorgeu

+0

... [공통 테이블 식] (http://www.postgresql.org/docs/9.0/static/queries-with.html)을 사용하십시오. – soulcheck

1

내가 알 수있는 바로는 ResultSet 객체를 사용하여 명령문 결과를 저장 한 다음 재귀 함수 호출에 매개 변수로 전달하는 것입니다. 그래서 기본적으로 변수를 덮어 쓰고 변수에 대한 참조를 잃어 버리는 것입니다. sql 문을 작성하여 필요한 데이터를 검색하거나 동일한 ResultSet 객체를 재귀 호출에 전달해야합니다. JDBC 문에 대한