2. 컴퓨터 이야기/프로그래밍

java.sql.ResultSet 작업시 쿼리한 값이 있는지 없는지 확인, isBeforeFirst()

래빗 크리스 2008. 12. 12. 09:49
ResultSet 에 쿼리 결과를 가져온 다음에,
도대체가 값을 읽어온 것이 있는지 없는지 알려면 어떻게 해야 할까..?
next() 메소드를 호출한 다음에 값이 있는지 확인하고 다시 첫번째로 돌리려고 first() 를 호출해야 할까..?
그런데, first() 메소드는 제대로 작동하지 않는다. 아무래도 버그.. ㅋ
그렇다면 어떻게 해야 할까..?
정답은 isBeforeFirst() 메소드.

isBeforeFirst() 는 쿼리한 결과의 커서가,
첫 로우 바로 앞이면 true,
첫 로우 바로 앞이 아니거나, 결과 로우가 없으면 false.

Context                 ctx        = new InitialContext();
DataSource           source  = (DataSource) ctx.lookup("...");
Connection            con      = source.getConnection();
String                    query    = "...";
PreparedStatement  pstmt    = con.prepareStatement(query);
ResultSet               rs        = pstmt.executeQuery();

if(rs!=null && rs.isBeforeFirst()){
  ...
}


다음은 해당 기술 내용이다.

    /**
     * Retrieves whether the cursor is before the first row in
     * this <code>ResultSet</code> object.
     *
     * @return <code>true</code> if the cursor is before the first row;
     * <code>false</code> if the cursor is at any other position or the result set contains no rows
     * @exception SQLException if a database access error occurs
     * @since 1.2
     */
    boolean isBeforeFirst() throws SQLException;

그런데, ResultSet 에 값을 담아서 사용하기 보다는,
ResultSet 의 값을 ArrayList 에 담아서 사용하는 것이 더 나을 듯.
그리고 ArrayList 에 담을때 각 Row 의 값을 HashMap 에 담는 분이 있는데,
그렇게 하지 말고 Entity 형태의 Object 에 넣어서 ArrayList 에 담는 것이 다루기 쉽지 않나 싶다.