I have a MSSQL
database and am running the following query:
select * from projects; select * from user
The above query returns two result sets at once, and I cannot fire both queries separately. How can I handle both the result set at once in a Java class?
Create a Stored Procedure that has multiple selects, and fill the DataSet . The returned dataset will have a DataTable in it's Tables array for each select in the stored procedure. Show activity on this post. Show activity on this post.
Multiple Result Sets with the Execute SQL Task. In reality, data retrieval queries are typically configured to return exactly one result set. If two different result sets are needed, two separate queries are built, each with its own source-to-target flow of data.
In addition, when running a statement that returns more than one result set, you can use the execute method of the SQLServerStatement class, because it will return a boolean value that indicates if the value returned is a result set or an update count.
In order to get multiple result sets working we need to drop to the ObjectContext API by using the IObjectContextAdapter interface. Once we have an ObjectContext then we can use the Translate method to translate the results of our stored procedure into entities that can be tracked and used in EF as normal.
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()
and execute()
return false
to indicate that the result of the statement is just a number and not a ResultSet
.stmt.getUpdateCount() == -1
to know if there are more results.stmt.getMoreResults(Statement.CLOSE_CURRENT_RESULT)
You can use Statement.execute(), getResultSet();
PreparedStatement stmt = ... prepare your statement result boolean hasResults = stmt.execute(); while (hasResults) { ResultSet rs = stmt.getResultSet(); ... your code parsing the results ... hasResults = stmt.getMoreResults(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With