1. 关于oracle和结果集
其实在大多数情况下,我们并不需要从oracle存储过程里返回一个或多个结果集,除非迫不得已。
如果大家用过ms sql server或sybase sql server,那么从存储过程返回一个动态的结果集是一件非常容易的事情,只要在存储过程结束时写上
“select column1,column2,.... from table_list where condition“
就可以了。
但在oracle中不能这样做. 我们必须使用oracle cursor.
在oracle pl/sql中,cursor用来返回一行或多行记录,借助cursor,我们可以从结果集中取得所有记录.
cursor并不难,但是要从oracle存储过程中返回结果集, 就需要用到cursor变量,cursor变量oracle pl/sql的类型是ref cursor, 我们只要定义了ref cursor 类型就可以使用cursor变量. 比如我们可以这样定义:
type ref_cursor is ref cursor;
了解了cursor以及cursor变量,下面就介绍如何使用cursor变量给jdbc返回结果集.
2. 定义表结构
在以下例子里,我们要用到一张表hotline.
create table hotline(country varchar2(50),pno varchar2(50));
3. 定义存储过程
create or replace package pkg_hotline istype hotlinecursortype is ref cursor;
function gethotline return hotlinecursortype;
end;
create or replace package body pkg_hotline isfunction gethotline return hotlinecursortype ishotlinecursor hotlinecursortype;
beginopen hotlinecursor for select * from hotline;
return hotlinecursor;
end;
end;
在这个存储过程里,我们定义了hotlinecursortype 类型,并且在存储过程中简单地查找所有的记录并返回hotlinecursortype.
4. 测试存储过程
在oracle sql/plus里登陆到数据库. 按以下输入就看到返回的结果集.
sql> var rs refcursor;sql> exec :rs := pkg_hotline.gethotline;sql> print rs;
5. java调用
简单地写一个java class.
....public void opencursor(){connection conn = null;resultset rs = null;
callablestatement stmt = null;
string sql = “{? = call pkg_hotline.gethotline()}“;
try{conn = getconnection();stmt = conn.preparecall(sql);
stmt.registeroutparameter(1,oracletypes.cursor);
stmt.execute();
rs = ((oraclecallablestatement)stmt).getcursor(1);
while(rs.next()){string country = rs.getstring(1);
string pno = rs.getstring(2);
system.out.println(“country:“+country+“|pno:”+pno);
}}catch(exception ex){ex.printstacktrace();
}finally{closeconnection(conn,rs,stmt);
}}.....
好了,大功告成.
闽公网安备 35060202000074号