---
title: "JAVA调用ORACLE存储过程小结"
author: "zhkac"
date: "2010-06-13T08:27:21Z"
tags: ["JDBC", "Java", "Oracle", "SQL"]
categories: ["数据库"]
slug: "java-oracle"
draft: false
lastmod: "2010-06-13T08:27:21Z"
id: 691041
url: "https://zhkac.iteye.com/blog/691041"
---

一、无返回值的存储过程

       存储过程为：（该过程为向dept添加部门）

create or replace procedure adddept(deptno number,dname varchar2,loc varchar2)

as

begin

     if deptno is not null then

        insert into dept values(deptno,dname,loc);

        commit;

     else

         null;

     end if;

end adddept;

/

然后在JAVA里调用就用下面的代码

public class TestProcedure{

       Connection conn = null;

       CallabledStatement cstmt = null;

       PreparedStatement pstmt = null;

       String url=”jdbc:oracle:thin:@localhost:1521:mydb”;

       String driver=”oracle.jdbc.driver.OracleDriver”;

       String name=””

       public TestProcedure {

              try{

                     Class.forName(dirver);

                     Conn=DriverManager.getConnection(url,”scott”,”tiger”);

                     cstmt=conn,prepareCall(“{call adddept(?,?,?)}”);

                     cstmt.setInt(1,80);

                     cstmt.setString(2,”总部”);

                     cstmt.setString(3,”beijing”);

                     cstmt.executeUpdate();

              Systemt.out.println(“success”);

              }catch(Exception e){

e.printStackTrace();

}finally{

       cstmt.close();

conn.close();

}

       }

}

【注：dept表为oracle数据库方案scott中的一个表】

 

二、有返回值的存储过程（非列表）

IN表示向存储过程传递参数，OUT表示从存储过程返回参数

存储过程为：(根据雇员号查工资)

create or replace procedure selemp\_sal (para1 in number,para2 out number)

as

begin

select sal into para2 from emp where empno=para1;

end selemp\_sal;

/

在数据库的SQL窗口中调用：

declare    

vstr2   varchar2(10);

begin 

 selemp\_sal(7654,vStr2);--//7654为雇员号

 dbms\_output.put\_line(vStr2);  

end;

在JAVA里调用就用下面的的代码：

public class SelSalary(){

       public SelSalary(){}//构造函数

       public static void main(String\[] args){

              String driver=”oracle.jdbc.driver.OracleDriver”;

              String url=”jdbc:oracle:thin:@localhost:1521:mydb”;

              Statement stmt=null;

              ResuultSet rs=null;

Connection conn=null;

try{

       Class.forName(driver);

       conn=DriverManager.getConnection(url,”scott”,”tiger”);

       CallableStatement cstmt=null;

       cstmt=conn..prepareCall(“{call selemp\_sal(?,?)}”);

       cstmt..setInt(1, 7654);

       cstmt.registerOutparameter(2,Types.VARCHAR);

       cstmt.execute();

       String thesal=cstmt.getString(2);

       System.out.pringln(“The people’s salary is ”+thesal);

}catch(Exception ex){

ex.printStatckTrace();

}finally{

       if(rs!=null) rs.close();

       if(stmt!=null) stmt.close();

       if(conn!=nill) conn.close();

}

}

}

}

【注：emp表为oracle数据库方案scott中的一个表,

这里的cstmt.getString(2) 中的数值2并非任意的，而是和存储过程的out列对应的，如果out是在第一个位置，那就是cstmt.getString(1)，如果out是在第三个位置，那就是cstmt.getString(3)，当然可以有多个返回值，那就是多增加几个out参数啦】

三、返回列表

       由于oracle 存储过程没有返回值，他的所有返回值都是通过out参数来替代的，列表也同样不例外，但由于是集合，所以不能用一般的参数，必须要用pagkage了，所以要分两部分，

1\. 建立一个程序包，如下：

       create or replace package mypackage as

       TYPE my\_cursor is REF CURSOR;

       end mypackage;

2.建立存储过程，存储过程为：（查询工资等级）

       create or replace procedure selsal\_grade (p\_cur out mypackage.my\_cursor)

as

begin

open p\_cur for select * from salgrade;

end selsal\_grade;

可以看到，它把一个游标（可以理解为一个指针），作为一个out参数来返回的

在Oracle的SQL窗口中调用用下面的代码：

declare    

v\_cur mypackage.my\_cursor;

grad salgrade%rowtype;

begin

 selsal\_grade(v\_cur);

 dbms\_output.put\_line('等级   最高工资   最低工资');

 loop

 fetch v\_cur into grad;

 exit when v\_cur%NOTFOUND;

 dbms\_output.put\_line(grad.grade||'      '||grad.losal||'      '||grad.hisal); 

 end loop;

 --dbms\_output.put\_line(v\_cur%rowcount); 

 close v\_cur;

end;

在JAVA里调用就用下面的代码：

public class selectGrade(){

public selectGrade(){};//构造函数

public static void main(String\[] args){

              String driver=”oracle.jdbc.driver.OracleDriver”;

              String url=”jdbc:oracle:thin:@localhost:1521:mydb”;

              Statement stmt=null;

              ResuultSet rs=null;

Connection conn=null;

 

try{

       Class.forName(driver);

       conn=DriverManager.getConnection(url,”scott”,”tiger”);

       CallableStatement cstmt=null;

       cstmt=conn..prepareCall(“{call selsal\_grade (?)}”);

       cstmt.registerOutParameter(1,oracle.jdbc.OracleTypes.CURSOR);

       cstmt.execute();

       rs=(ResultSet) cstmt.getObject(1);

       System.out.println(“等级   最高工资   最低工资”);

       while(rs.next())

{

              System.out.println(rs.getString(1)+”  ”|+rs.getString(2)+”  ”+rs.getString(3));

}

              }catch(Exception e)

              {

                     e.printStackTrace();

} finally{

       if(rs!=null) rs.close();

       if(stmt!=null) stmt.close();

       if(conn!=nill) conn.close();

}

}

}