Java调用Oracle存储过程

1:首先你需要创建一个包,并定义你返回的游标的类型、存储过程
create or replace package TEST_PKG is
type cur_emp is REF CURSOR;
procedure test_proc (emps out cur_emp);
end TEST_PKG;
2:然后你再创建包体
create or replace package body TEST_PKG is
procedure test_proc (emps out cur_emp)
as 
begin 
open emps for select * from student;
end test_proc; 
end TEST_PKG;
3: 通过JAVA调用
(1)连接oracle函数【需要导入相应包】
import java.sql.*;
import oracle.jdbc.driver.OracleDriver;

public class oracleConn
{
  Connection conn=null;
  String driver="oracle.jdbc.driver.OracleDriver";
  String url="jdbc:oracle:thin:@localhost:1521:lianxi";
  public Connection oracleGetConn(){
  try
  {
   Class.forName(driver);
   conn=DriverManager.getConnection(url,"system","chang");
  }
  catch(Exception e)
  {
   System.out.println("数据库连接失败,原因如下所示:");
   e.printStackTrace();
  }
   return conn;
  }
}
(2)测试
import java.sql.*;
public class oracleConnPro
{
 public static void main(String[] args)
 {
  try
  {
   oracleConn oc=new oracleConn();
   Connection conn=oc.oracleGetConn();
   CallableStatement cstmt = conn.prepareCall("{call TEST_PKG.test_proc (?)}");
   cstmt.registerOutParameter(1,oracle.jdbc.OracleTypes.CURSOR);
   cstmt.execute();
   
   ResultSet rs = (ResultSet)cstmt.getObject(1);
   System.out.println("------【Java连接Oracle数据库存储过程测试】------");
   System.out.println("----------------------------------------------");
   System.out.println("学号"+"/t"+"姓名"+"/t"+"性别"+"/t"+"年龄"+"/t"+"专业");
   System.out.println("----------------------------------------------");
   while(rs.next())
   {
    System.out.println(rs.getString(1)+"/t"+rs.getString(2)+"/t"+
    rs.getString(3)+"/t"+rs.getString(4)+"/t"+rs.getString(5));
   }
   rs.close();
   conn.close();
  }
  catch(Exception e)
  {
  e.printStackTrace();
 }
 }
}

你可能感兴趣的:(Oracle,Java,oracle,java,存储,exception,import,string)