Search code examples
resultsetspring-jdbcjdbctemplate

How to Iterate through ResultSet


My SELECT_QUERY_RETURNS_LIST returns 5 results, But following while loop prints only 4.

jdbcTemplate.query(SELECT_QUERY_RETURNS_LIST, new RowCallbackHandler() {
    public void processRow(ResultSet resultSet) throws SQLException {
        int count = 1;
        while (resultSet.next()) {
            String payload = resultSet.getString(1);
            LOGGER.info("My result {}...",count++);
        }
    }
});

Logically It is correct as spring jdbc RowCallbackHandler tells

rs - the ResultSet to process (pre-initialized for the current row)

In firstline Itself we told resultSet.next(), So It starts from second record which results in printing 4 records. And following code works as my expcectation

jdbcTemplate.query(SELECT_QUERY_RETURNS_LIST, new RowCallbackHandler() {
    public void processRow(ResultSet resultSet) throws SQLException {
        int count = 1;
        String payload = resultSet.getString(1);
        LOGGER.info("My result {}...",count++);
        while (resultSet.next()) {
            payload = resultSet.getString(1);
            LOGGER.info("My result {}...",count++);
        }
    }
});

So please tell solution to minimize code before while loop.


Solution

  • Issue has been resolved by using do while instead of while loop

    jdbcTemplate.query(SELECT_QUERY_RETURNS_LIST, new RowCallbackHandler() {
        public void processRow(ResultSet resultSet) throws SQLException {
            int count = 1;
            do {
                payload = resultSet.getString(1);
                LOGGER.info("My result {}...",count++);
            } while (resultSet.next());
        }
    });