在我们基于 Oracle(11g) 的应用程序中,我们大量使用了流水线函数。现在事实证明,从这些函数报告错误很困难,如下面的(缩减)示例所示。该过程的存在是为了从 Java 中调用,它应该接收在 PL/SQL 执行期间任何地方发生的错误。
甲骨文部分:
set serveroutput on
create table dummy (id NUMBER);
create or replace package mytest
as
type t_rec is record (id integer);
type t_tab is table of t_rec;
type t_ref_cur IS REF CURSOR RETURN t_rec;
function foo
return t_tab pipelined;
procedure bar( p_ref_cur out t_ref_cur);
end mytest;
/
show errors
create or replace package body mytest
as
function foo
return t_tab pipelined
is
v_cur SYS_REFCURSOR;
v_sql varchar2(2000);
v_rec t_rec;
begin
v_sql := 'select wrong_column from DUMMY';
open v_cur for v_sql;
loop
fetch v_cur into v_rec;
exit when v_cur%notfound;
pipe row (v_rec);
end loop;
exception
when no_data_needed then
null;
when others then
dbms_output.put_line(SQLCODE||' '||sqlerrm );
raise no_data_found;
end foo;
procedure bar( p_ref_cur out t_ref_cur)
is
begin
open p_ref_cur for select * from table(foo);
end bar;
end mytest;
/
show errors
-- call procedure bar() from pl/sql
set serveroutput on
declare v_ref_cur mytest.t_ref_cur;
v_rec mytest.t_rec;
begin
mytest.bar(v_ref_cur);
loop
fetch v_ref_cur into v_rec;
exit when v_ref_cur%notfound;
dbms_output.put_line(v_rec.id);
end loop;
end;
/
show errors
运行上述函数会导致显示异常:
ORA-00904: "WRONG_COLUMN": invalid column name
Java部分:
package test1;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import oracle.jdbc.OracleTypes;
public class start {
public static void main(String[] args)
{
try
{
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@...", "…", "…");
CallableStatement stmt = con.prepareCall("BEGIN mytest.bar(?); END;");
stmt.registerOutParameter(1, OracleTypes.CURSOR);
stmt.executeQuery();
ResultSet rs = (ResultSet)stmt.getObject(1);
while (rs.next())
{
System.out.println(rs.getInt(1));
}
stmt.close();
con.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
异常不会被捕获。结果集为空。
这是预期的行为吗?我们做错了什么吗?是否存在解决方法?