Correct code to process multiple ResultSet
s returned by a JDBC statement:
PreparedStatement stmt = ...;
boolean isResultSet = stmt.execute();
int count = 0;
while(true) {
if(isResultSet) {
rs = stmt.getResultSet();
while(rs.next()) {
processEachRow(rs);
}
rs.close();
} else {
if(stmt.getUpdateCount() == -1) {
break;
}
log.info("Result {} is just a count: {}", count, stmt.getUpdateCount());
}
count ++;
isResultSet = stmt.getMoreResults();
}
Important bits:
getMoreResults()
andexecute()
returnfalse
to indicate that the result of the statement is just a number and not aResultSet
.- You need to check
stmt.getUpdateCount() == -1
to know if there are more results. - Make sure you either close the result sets or use
stmt.getMoreResults(Statement.CLOSE_CURRENT_RESULT)