有表test,以下是测试数据:
select * from test;
id info
----------------------
1 测试数据1
2 测试数据2
3 测试数据3
4 测试数据4
5 测试数据5
6 测试数据6
7 测试数据7
8 测试数据8
9 测试数据9
10 测试数据10
11 测试数据11
12 测试数据12
13 测试数据13
编写存储过程如下:
create or replace procedure test1(
n IN number, --输入参数,主键id
info1 OUT varchar2 --输出参数,此存储过程只能返回单个值
)
as
begin
select info into info1 from test where id=n;
end;
/
ORACLE的调用方式为:
declare
accp varchar2(20);
begin
test1(10,accp);
DBMS_OUTPUT.PUT_LINE(accp);
end;
/
JAVA程序的调用方式为:
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@192.168.10.77:1521:ora10","scott","tiger");
System.out.println(conn);
CallableStatement stm=conn.prepareCall("{call test1(?,?)}");
stm.setInt(1, 10);
stm.registerOutParameter(2, Types.VARCHAR);
stm.execute();
String info=stm.getString(2);//根据索引2得到输出参数的值
System.out.println(info);
conn.close();
如果是以游标作为参数,就是能返回多条记录,则存储过程如下:
1、 建一个程序包。如下:
create or replace package testpackage as
type test_CURSOR IS REF CURSOR;
end testpackage;
2、建一个存储过程,如下:
create or replace procedure test2(p_CURSOR out testpackage.test_CURSOR)
IS
begin
open p_CURSOR for select * from test;
end test2;
/
3、在JAVA中调用此存储过程:
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@192.168.10.77:1521:ora10","scott","tiger");
System.out.println(conn);
CallableStatement stm=conn.prepareCall("{call test2(?)}");
stm.registerOutParameter(1,oracle.jdbc.OracleTypes.CURSOR);
stm.execute(); --不能使用executeQuery()
ResultSet rs=(ResultSet)stm.getObject(1);
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
conn.close();
[b]调用无入参的函数[/b]
地址:http://www.blogjava.net/keweibo/articles/270153.html
调用无入参的函数
函数定义CREATE OR REPLACE Function f_getstring Return Varchar2 Is
Begin
Return ''String value'';
End f_getstring;
调用函数的Java 片断 CallableStatement cstmt = con.prepareCall("{?=call f_getstring}");
cstmt.registerOutParameter(1, Types.VARCHAR);
cstmt.execute();
String strValue = cstmt.getString(1);
System.out.println("The return value is:" + strValue);
cstmt.close();
调用有一个入参,一个输出参数以及一个字符串返回值的函数
函数定义CREATE OR REPLACE Function f_Getinfo(Id Integer, Age Out Integer) Return Varchar2 Is
Begin
Age := 10;
Return ''The age is:'' || Id;
End f_Getinfo;
调用函数的Java代码片断 CallableStatement cstmt = con
.prepareCall("{?=call f_getinfo(?,?)}");
cstmt.registerOutParameter(1, Types.VARCHAR);
cstmt.setInt(2, 11);
cstmt.registerOutParameter(3, Types.INTEGER);
cstmt.execute();
String strValue = cstmt.getString(1);
int age = cstmt.getInt(3);
System.out.println("The return value is:" + strValue
+ " and age is:" + age);
cstmt.close();
[b]java oracle存储过程/函数(1):字符串数组、int数组传入存储过程 [/b]
http://blog.csdn.net/crazylaa/article/details/5171881
[b]java oracle存储过程/函数(2):字符串数组传出存储过程,动态sql如何fetch到游标[/b]
http://blog.csdn.net/crazylaa/article/details/5171973