Skip to content

Instantly share code, notes, and snippets.

@harawata
Created April 16, 2023 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harawata/66ccb4189d0e21a5eb9e383c52695523 to your computer and use it in GitHub Desktop.
Save harawata/66ccb4189d0e21a5eb9e383c52695523 to your computer and use it in GitHub Desktop.
JDBC test that is supposed to retrieve two result sets from Oracle DB
@Test // so-76023096 tested with Oracle 19.3 ojdbc 23.2.0.0
void testMultipleResultSets() throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@127.0.0.1:1521/orclpdb1";
String username = "system";
String password = "oracle123";
try (Connection con = DriverManager.getConnection(url, username, password)) {
try (Statement st = con.createStatement()) {
try {
st.execute("drop TABLE author");
} catch (SQLException e) {
//
}
try {
st.execute("drop TABLE book");
} catch (SQLException e) {
//
}
st.execute("create table author (id int, name varchar(10), publish_id int)");
st.execute("create table book (publish_id int, book_id varchar(10), book_name varchar(10))");
st.executeUpdate("insert into author (id, name, publish_id) values (1, 'John', 123)");
st.executeUpdate("insert into author (id, name, publish_id) values (2, 'Jane', 345)");
st.executeUpdate("insert into book (publish_id, book_id, book_name) values (123, 'B101', 'C#')");
st.executeUpdate("insert into book (publish_id, book_id, book_name) values (123, 'B102', 'Python')");
st.executeUpdate("insert into book (publish_id, book_id, book_name) values (345, 'J001', 'SQL')");
st.executeUpdate("insert into book (publish_id, book_id, book_name) values (345, 'J002', 'Java')");
}
String sql = """
declare
author_curs sys_refcursor;
book_curs sys_refcursor;
begin
open author_curs for select * from author order by id;
dbms_sql.return_result(author_curs);
open book_curs for select * from book order by publish_id;
dbms_sql.return_result(book_curs);
end;
""";
try (CallableStatement stmt = con.prepareCall(sql)) {
stmt.execute();
// The following line throws SQLException ORA-17283
// The javadoc says SQLException is thrown 'if a
// database access error occurs or this method
// is called on a closed Statement' which is not
// applicable here.
// It should return eitehr 1) the first result set
// or 2) null
try (ResultSet rs = stmt.getResultSet()) {
while (rs.next()) {
System.out.println(rs.getString("id"));
System.out.println(rs.getString("name"));
System.out.println(rs.getInt("publish_id"));
}
}
assertTrue(stmt.getMoreResults());
try (ResultSet rs = stmt.getResultSet()) {
while (rs.next()) {
System.out.println(rs.getInt("publish_id"));
System.out.println(rs.getString("book_id"));
System.out.println(rs.getString("book_name"));
}
}
assertFalse(stmt.getMoreResults());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment