怎么样利用游标返回结果集?
第一种方法:
*过程返回记录集:
CREATE OR REPLACE PACKAGE pkg_test
AS
TYPE myrctype IS REF CURSOR;
PROCEDURE get (p_id NUMBER, p_rc OUT myrctype);
END pkg_test;
/
CREATE OR REPLACE PACKAGE BODY pkg_test
AS
PROCEDURE get (p_id NUMBER, p_rc OUT myrctype)
IS
sqlstr VARCHAR2 (500);
BEGIN
IF p_id = 0 THEN
OPEN p_rc FOR
SELECT ID, NAME, sex, address, postcode, birthday
FROM student;
ELSE
sqlstr :=
´select id,name,sex,address,postcode,birthday
from student where id=:w_id´;
OPEN p_rc FOR sqlstr USING p_id;
END IF;
END get;
END pkg_test;
/
函数返回记录集:
建立带ref cursor定义的包和包体及函数:
CREATE OR REPLACE
package pkg_test as
/* 定义ref cursor类型
不加return类型,为弱类型,允许动态sql查询,
否则为强类型,无法使用动态sql查询;
*/
type myrctype is ref cursor;
--函数申明
function get(intID number) return myrctype;
end pkg_test;
/
CREATE OR REPLACE
package body pkg_test as
--函数体
function get(intID number) return myrctype is
rc myrctype; --定义ref cursor变量
sqlstr varchar2(500);
begin
if intID=0 then
--静态测试,直接用select语句直接返回结果
open rc for select id,name,sex,address,postcode,birthday from
student;
else
--动态sql赋值,用:w_id来申明该变量从外部获得
sqlstr := ´select id,name,sex,address,postcode,birthday from
student where id=:w_id´;
--动态测试,用sqlstr字符串返回结果,用using关键词传递参数
open rc for sqlstr using intid;
end if;
return rc;
end get;
end pkg_test;
第二种方法:
在sqlplus中建立如下的内容:
1,程序包
SQL> create or replace package types
as
type cursorType is ref cursor;
end;
程序包已创建。
2、函数
SQL> create or replace function sp_ListEmp return types.cursortype
as
l_cursor types.cursorType;
begin
open l_cursor for select id, title from cf_news order by id;--表的名字
return l_cursor;
end;
函数已创建。
3、过程
SQL> create or replace procedure getemps( p_cursor in out types.cursorType )
as
begin
open p_cursor for select id, title from cf_news order by id;--表的名字
end;
过程已创建。
4、建立一个可执行的java控制台程序
import java.sql.*;
import java.io.*;
import oracle.jdbc.driver.*;
class GetValues
{
public static void main (String args [])
throws SQLException, ClassNotFoundException
{
String driver_class = "oracle.jdbc.driver.OracleDriver";
String connect_string = "jdbc:oracle:thin:@127.0.0.1:1521:database";
String query = "begin :1 := sp_listEmp; end;"; //此处调用前面建立的函数!
Connection conn;
Class.forName(driver_class);
conn = DriverManager.getConnection(connect_string, "scott", "tiger");
CallableStatement cstmt = conn.prepareCall(query);
cstmt.registerOutParameter(1,OracleTypes.CURSOR);
cstmt.execute();
ResultSet rset = (ResultSet)cstmt.getObject(1);
while (rset.next ())
System.out.println( rset.getString (1) );
cstmt.close();
}
}
本文地址:http://www.45fan.com/dnjc/71350.html