码迷,mamicode.com
首页 > 数据库 > 详细

做一个,记一篇 — Java调用Oracle存储过程

时间:2018-05-18 23:27:08      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:jdb   url   varchar   ring   final   catch   result   create   except   

一、需求

        传入一个参数,返回多条记录(列表)。

 

二、实现步骤

  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存储过程

标签:jdb   url   varchar   ring   final   catch   result   create   except   

原文地址:https://www.cnblogs.com/maxiaolang/p/9058365.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!