1、创建表:
create table stud(
sid int,
sname varchar2(50)
)
并插入一条数据
insert into stud values(1,'Tom')
2、通过包定义一个游标
create or replace package pack_stud
is
--声明一个游标类型
type cur is ref cursor;
end;
3、创建存储过程
create or replace procedure pro_select_stud(
my_cur out pack_stud.cur
)
is
begin
open my_cur for select * from stud;
end;
4、jdbc中调用
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import oracle.jdbc.driver.OracleTypes;
public class TestProCur {
public void test(){
Connection con = null;
ResultSet rs = null;
CallableStatement cst = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
//下面的tan是数据库名,默认是orcl,love是访问密码,默认是tiger,
//1521是端口号,默认是1521
con = DriverManager.getConnection ("jdbc:oracle:thin:@192.168.1.103:1521:tan","scott","love");
String sql = "{call pro_select_stud(?)}";
cst = con.prepareCall(sql);
cst.registerOutParameter(1, OracleTypes.CURSOR);
cst.execute();
rs = (ResultSet)cst.getObject(1);
while(rs.next()){
System.out.println(rs.getString(2));
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(rs !=null){
rs.close();
}
if(cst != null){
cst.close();
}
if(con != null){
con.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
TestProCur tpc = new TestProCur();
tpc.test();
}
}