CallableStatement调用Oracle存储过程返回结果集(ResultSet)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Java(CallableStatement)调用Oracle存储过程返回结果集(ResultSet) 一:无返回值的存储过程调用
存储过程:
CREATE OR REPLACE PROCEDURE PRO_1(PARA1 IN VARCHAR2,PARA2 IN VARCHAR2) AS
BEGIN
INSERT INTO DBO.EMP (ID,NAME) VALUES (PARA1, PARA2);
END PRO_1;
Java代码:
package com.icesoft.service;
import java.sql.*;
import java.sql.ResultSet;
public class CallProcedureTest1 {
public CallProcedureTest1() {
super();
}
public static void main(String[] args) {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl ";
String user = "admin";
String pwd = "password";
Connection conn = null;
CallableStatement cs = null;
ResultSet rs = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, pwd);
cs = conn.prepareCall("{ call DBO.PRO_1(?,?) }");
cs.setString(1, "10");
cs.setString(2, "Peter");
cs.execute();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (cs != null) {
cs.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
}
}
}
}
备注,存储过程PRO_1中用到了表EMP(ID, NAME),需事先建好
二:有返回值的存储过程(非结果集)
存储过程:
CREATE OR REPLACE PROCEDURE PRO_2(PARA1 IN VARCHAR2,PARA2 OUT VARCHAR2) AS
BEGIN
SELECT INTO PARA2 FROM EMP WHERE ID= PARA1;
END PRO_2;
Java代码:
package com.icesoft.service;
import java.sql.*;
public class CallProcedureTest2 {
public CallProcedureTest2() {
super();
}
public static void main(String[] args) {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; String user = "admin";
String pwd = "password";
Connection conn = null;
CallableStatement cs = null;
ResultSet rs = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, pwd); cs = conn.prepareCall("{ call DBO.PRO_2(?,?) }");
cs.setString(1, "10");
cs.registerOutParameter(2, Types.VARCHAR);
cs.execute();
String name = cs.getString(2);
System.out.println("name: " + name);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (cs != null) {
cs.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
}
}