Search code examples
javaresultset

How to handle case where 0, 1, or 2 rows are returned from ResultSet


I have a ResultSet resultSet that can potentially return 0, 1, or 2 rows from an executed query.

Map<String, Integer> results = new HashMap<>();
if (!resultSet.next()){
     // handle case where there are no rows
     results.put("count1", 0)
     results.put("count2", 0)
}
else {
     resultSet.beforeFirst();
     while (resultSet.next()) {
     // handle case where there are 1 or 2 rows
     results.put(resultSet.getInt("column1") == 0 ? "count1" : "count2", resultSet.getInt("column2"));
     }
}

When there are no rows or 1 row, I get this exception org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0. Shouldn't my if condition handle no rows and shouldn't my else condition also handle 1 row. My else condition is able to handle 2 rows.


Solution

  • The problem ended up being how I was calling the query from another class. I was using the QueryExecutor method queryForObject that expects a single result to be returned, so when my query executed and no rows returned, EmptyResultDataAccessException got thrown. When I changed the method to query, then:

    while (resultSet.next()) {
         results.put(resultSet.getInt("column1") == 0 ? "count1" : "count2", resultSet.getInt("column2"));
    }
    

    worked with no issues since the while loop won't execute if there are no rows.