使用 JDBC 从 dbms_output.get_lines 获取输出
如何使用JDBC在Java应用程序中获取Oracle的输出,而无需在数据库中创建其他对象?dbms_output.get_lines
如何使用JDBC在Java应用程序中获取Oracle的输出,而无需在数据库中创建其他对象?dbms_output.get_lines
我也在这里写了关于这个问题的博客。下面是一个代码段,说明了如何执行此操作:
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]
请注意,/ 设置是连接范围的设置,因此您也可以通过多个 JDBC 语句执行此操作:ENABLE
DISABLE
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
以前,有一个现已删除的应答建议改为单个呼叫,该应答一次返回一行。我已经将方法与 进行了基准测试,并且差异很大 - 从JDBC调用时速度慢了30倍(即使从PL / SQL调用过程时并没有太大的差异)。DBMS_OUTPUT.GET_LINE
DBMS_OUTPUT.GET_LINES
因此,使用批量数据传输方法绝对值得。以下是基准测试的链接:DBMS_OUTPUT.GET_LINES
https://blog.jooq.org/2017/12/18/the-cost-of-jdbc-server-roundtrips/