I've also blogged about this issue here。这是一个说明如何做到这一点的 sn-p:
try (CallableStatement call = c.prepareCall(
"declare "
+ " num integer := 1000;" // Adapt this as needed
+ "begin "
// You have to enable buffering any server output that you may want to fetch
+ " dbms_output.enable();"
// This might as well be a call to third-party stored procedures, etc., whose
// output you want to capture
+ " dbms_output.put_line('abc');"
+ " dbms_output.put_line('hello');"
+ " dbms_output.put_line('so cool');"
// This is again your call here to capture the output up until now.
// The below fetching the PL/SQL TABLE type into a SQL cursor works with Oracle 12c.
// In an 11g version, you'd need an auxiliary SQL TABLE type
+ " dbms_output.get_lines(?, num);"
// Don't forget this or the buffer will overflow eventually
+ " dbms_output.disable();"
+ "end;"
)) {
call.registerOutParameter(1, Types.ARRAY, "DBMSOUTPUT_LINESARRAY");
call.execute();
Array array = null;
try {
array = call.getArray(1);
System.out.println(Arrays.asList((Object[]) array.getArray()));
}
finally {
if (array != null)
array.free();
}
}
上面将打印:
[abc, hello, so cool, null]
请注意,ENABLE / DISABLE 设置是连接范围的设置,因此您也可以通过多个 JDBC 语句执行此操作:
try (Connection c = DriverManager.getConnection(url, properties);
Statement s = c.createStatement()) {
try {
s.executeUpdate("begin dbms_output.enable(); end;");
s.executeUpdate("begin dbms_output.put_line('abc'); end;");
s.executeUpdate("begin dbms_output.put_line('hello'); end;");
s.executeUpdate("begin dbms_output.put_line('so cool'); end;");
try (CallableStatement call = c.prepareCall(
"declare "
+ " num integer := 1000;"
+ "begin "
+ " dbms_output.get_lines(?, num);"
+ "end;"
)) {
call.registerOutParameter(1, Types.ARRAY, "DBMSOUTPUT_LINESARRAY");
call.execute();
Array array = null;
try {
array = call.getArray(1);
System.out.println(Arrays.asList((Object[]) array.getArray()));
}
finally {
if (array != null)
array.free();
}
}
}
finally {
s.executeUpdate("begin dbms_output.disable(); end;");
}
}
另请注意,这将获取最多 1000 行的固定大小。如果需要更多行,您可能需要循环 PL/SQL 或轮询数据库。
关于调用DBMS_OUTPUT.GET_LINE 的说明
以前,有一个现已删除的答案建议单独调用 DBMS_OUTPUT.GET_LINE,而不是一次返回一行。我已经将该方法与DBMS_OUTPUT.GET_LINES 进行了基准比较,并且差异非常大 - 从 JDBC 调用时速度会慢 30 倍(即使从 PL/SQL 调用过程时并没有太大差异)。
因此,使用DBMS_OUTPUT.GET_LINES 的批量数据传输方法绝对值得。这是基准测试的链接:
https://blog.jooq.org/2017/12/18/the-cost-of-jdbc-server-roundtrips/