Java 开发中之七:oracle中的子程序之在JAVA中如何调用存储过程,函数。
存储过程
create or replace procedure p1(pnm varchar2,psal out number)
as
cursor ca is select * from emp where ename=upper(pnm);
v_ca ca%rowtype;
begin
for v_ca in ca loop
psal:=v_ca.sal;
end loop;
exception
when others then
dbms_output.put_line(sqlerrm);
end ;
SQL> var sal varchar2;
SQL> exec p1('smith',:sal);
在JAVA中调用
Connection connection=null;
CallableStatement statement=null;
OracleConnection conn=null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
//DriverManager.registerDriver("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@127.0.0.1:1521:ORCL";
String user="scott";
String password="tiger";
//下面是標準的的連接對象
//connection= DriverManager.getConnection(url, user, password);
//下面是在標準的連接不上時可以考慮的
conn=(OracleConnection) DriverManager.getConnection(url, user, password);
String strsql="{call p1(?,?)}";//
statement=conn.prepareCall(strsql);//调用
//传参
statement.setString(1, "smith");//in
statement.registerOutParameter(2, Types.FLOAT);//out
statement.execute();//执行
float sal= statement.getFloat(2);//取得內容
System.out.println(sal);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
finally
{
if(conn!=null)
{
conn.close();
}
if(connection!=null){
connection.close();
}
if(statement!=null){
statement.close();
}
}
函数的调用
create or replace function f1(pnm varchar2)
return number --函数一定有返回值
as
v_sal number;
begin
select sal into v_sal from emp where ename=upper(pnm);
return v_sal;
exception
when others then
dbms_output.put_line(sqlerrm);
end;
如下是调这个函数的语句块
declare
v_s number;
begin
v_s:=f1('smith');
dbms_output.put_line(v_s);
end;
如下是JAVA中调用
Connection connection=null;
CallableStatement statement=null;
OracleConnection conn=null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
//DriverManager.registerDriver("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@127.0.0.1:1521:ORCL";
String user="scott";
String password="tiger";
//下面是標準的的連接對象
//connection= DriverManager.getConnection(url, user, password);
//下面是在標準的連接不上時可以考慮的
conn=(OracleConnection) DriverManager.getConnection(url, user, password);
String strsql="{?=call f1(?)}";
statement= conn.prepareCall(strsql);
statement.setString(2, "smith");
statement.registerOutParameter(1, Types.FLOAT);
statement.execute();
float f= statement.getFloat(1);
System.out.println(f);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
finally
{
if(conn!=null)
{
conn.close();
}
if(connection!=null){
connection.close();
}
if(statement!=null){
statement.close();
}
}
总结:函数和存储过程的传入的参数类型:varchar2 number date emp.sal%type pl/sql中的表(数组) 引用的游标
缺点:返回值:单值,对集合数据没有用,所有就有下章节的程序包出现了
posted on 2012-12-11 20:55 peter.peng 阅读(291) 评论(0) 收藏 举报