csel
csel

Reputation: 317

Resultset's first row is skipped when while(rs.next) is executed in Java

I'm trying to get a result set of a SQL query in a java class. The problem is that the first row of my table is never displayed on my UI. So I debugged it.

When the while loop is first executed, while(rs.next) line executes then it does not go in to the loop, return backs to the beginning of while loop and executes while(rs.next) line again, now it goes into the while loop and sets the result set.

But since it does not go into the loop in the first time, the first row of my table is not set into the result set.

I could not find the problem here.

I tried do{} while(rs.next) but some times it throws exhausted result set exception

    String SQL_QUERY = select * from my_table;
Statement stt = null;
stt= conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 
    ResultSet.CONCUR_UPDATABLE,
                ResultSet.HOLD_CURSORS_OVER_COMMIT);

ResultSet rs = stt.executeQuery(SQL_QUERY);
if (rs != null) {
    rs.absolute(startRow); // I need to go to some specific row according to users request that is why I used this
} 

while(rs.next){
    // rs.getString...
}

Upvotes: 0

Views: 2712

Answers (2)

user8616404
user8616404

Reputation:

You are starting at startRow + 1 because you set rs.next after rs.absolute. Just change this and it will work.

String SQL_QUERY = select * from my_table;
Statement stt = null;
stt= conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 
ResultSet.CONCUR_UPDATABLE,
            ResultSet.HOLD_CURSORS_OVER_COMMIT);

ResultSet rs = stt.executeQuery(SQL_QUERY);
if (rs != null) {
rs.absolute(startRow); // here you are at row startRow
} 

while(rs.next()){
// and here you are at row startRow + 1
}

Upvotes: 2

talex
talex

Reputation: 20455

Replace while to

do {
    //old body here            
} while (rs.next())

This construction check condition after execution of the body. Effectively skipping first next call.

You may want to check result of rs.absolute(startRow). If it false then result set contains less than startRow rows.

Upvotes: 8

Related Questions