做一个,记一篇 — Java调用Oracle存储过程
Posted Shooting..............
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了做一个,记一篇 — Java调用Oracle存储过程相关的知识,希望对你有一定的参考价值。
一、需求
传入一个参数,返回多条记录(列表)。
二、实现步骤
1. 编写Oracle存储过程。
-- 声明包和包体的语句应该分两次执行,即使声明在前定义在后,如果一起执行依然会编译出错 -- 调用能够返回多条记录的存储过程需要定义在包内 --声明包及包内的游标、存储过程 CREATE OR REPLACE PACKAGE pack_myPackage IS TYPE myCursor IS REF CURSOR; PROCEDURE proc_querySomeInfo(pNo IN VARCHAR2, myCursor OUT myCursor); END myPackage; --定义包体 CREATE OR REPLACE PACKAGE BODY pack_myPackage IS PROCEDURE proc_querySomeInfo(pNo IN VARCHAR2, outcursor OUT myCursor) IS BEGIN OPEN outcursor FOR SELECT * FROM tableA WHERE P_NO = pNo; END proc_querySomeInfo; END pack_myPackage;
2. 编写Java代码
package vip.yaocn.test;import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet;/** * 存储过程测试 * * @author yacon */ public class ProcedureTest { public static void main(String[] args) throws Exception { String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; String driverName = "oracle.jdbc.driver.OracleDriver"; String username = "scott"; String password = "tiger"; Connection conn = null; CallableStatement cstmt = null; ResultSet rs = null; try { Class.forName(driverName); conn = DriverManager.getConnection(url, username, password); String callSql = "{call pack_myPackage.proc_getSomeInfo(?, ?) }"; cstmt = conn.prepareCall(callSql); cstmt.setString(1, "1001"); cstmt.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR); cstmt.execute(); rs = (ResultSet) cstmt.getObject(2); if (rs != null) { while (rs.next()) { System.out.println(rs.getString(1)); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (cstmt != null) { cstmt.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (conn != null) { conn.close(); } } catch (Exception e) { e.printStackTrace(); } } } }
3. 拓展知识
(1)
以上是关于做一个,记一篇 — Java调用Oracle存储过程的主要内容,如果未能解决你的问题,请参考以下文章