java访问oralce函数示例
Oracle中创建函数及过程代码如下:
|
--创建程序包头 create or replace package package_name as --使用过程查询工资大于2000的人数 procedure pro_count_sal (s in number,emp_sum out number); --使用过程查询工资大于2000的员工信息 procedure pro_emps_sal(s in number,cur out sys_refcursor); --使用函数查询工资大于2000的人数 function fun_count_sal(s in number) return number; --使用函数查询工资大于2000的员工信息 function fun_emps_sal(s in number) return sys_refcursor; end; --创建包体 create or replace package body package_name as --使用过程查询工资大于2000的人数 procedure pro_count_sal (s in number,emp_sum out number) as begin select count(1) into emp_sum from emp where sal > s; end; --使用过程查询工资大于2000的员工信息 procedure pro_emps_sal(s in number,cur out sys_refcursor) as begin open cur for select empno,ename,job,sal from emp where sal>s; end; --使用函数查询工资大于2000的人数 function fun_count_sal(s in number) return number as emp_count number; begin select count(1) into emp_count from emp where sal >s; return emp_count; end; --使用函数查询工资大于2000的员工信息 function fun_emps_sal(s in number) return sys_refcursor as cur sys_refcursor; begin open cur for select empno,ename,job,sal from emp where sal>s; return cur; end; end; |
java调用sql的语法
|
{call [包名.]过程[(?,?,..)]} |
说明:[]部分可以省略,问号表示参数
调用函数的语法
|
{?=call [包名.]函数名(?,?,...)} |
说明:
第一个?表示返回值,因为每一个函数必须要有一个返回值
在java中使用jdbc调用代码如下:
需要导入如下包:
|
import oracle.jdbc.OracleTypes; |
该类中的常量用于指明参数的数据类型
调用过程:
|
String sql="{call package_name.pro_count_sal(?,?)}"; CallableStatement call=conn.prepareCall(sql); //给第一个?赋值 call.setInt(1, 2000); //第二个?为输出参数要先注册,并指明类型 call.registerOutParameter(2, OracleTypes.NUMBER); //执行sql语句 call.execute(); //获取过程的返回值 int i=call.getInt(2); |
调用过程返回游标
|
String sql="{call package_name.pro_emps_sal(?,?)}"; CallableStatement call=conn.prepareCall(sql); //给第一个?赋值 call.setInt(1, 2000); //第二个?为输出参数要先注册,并指明类型 //因为返回的是游标,指明输出参数类型为cursor call.registerOutParameter(2, OracleTypes.CURSOR); //执行sql语句 call.execute(); //获取过程的返回值 ResultSet rst=(ResultSet) call.getObject(2); while(rst.next()){ //... } |

浙公网安备 33010602011771号