一:无返回值的存储过程
存储过程为:
CREATE OR REPLACE PROCEDURE TESTA(PARA1 IN VARCHAR2,PARA2 IN VARCHAR2) AS
BEGIN
INSERT INTO HYQ.B_ID (I_ID,I_NAME) VALUES (PARA1, PARA2);
END TESTA;
然后呢,在java里调用时就用下面的代码:
package com.hyq.src;
import java.sql.*;
import java.sql.ResultSet;
public class TestProcedureOne {
public TestProcedureOne() {
}
public static void main(String[] args ){
String driver = "oracle.jdbc.driver.OracleDriver";
String strUrl = "jdbc:oracle:thin:@127.0.0.1:1521: hyq ";
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
CallableStatement cstmt = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(strUrl, " hyq ", " hyq ");
CallableStatement proc = null;
proc = conn.prepareCall("{ call HYQ.TESTA(?,?) }");
proc.setString(1, "100");
proc.setString(2, "TestOne");
proc.execute();
}
catch (SQLException ex2) {
ex2.printStackTrace();
}
catch (Exception ex2) {
ex2.printStackTrace();
}
finally{
try {
if(rs != null){
rs.close();
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
}
}
catch (SQLException ex1) {
}
}
}
}
当然了,这就先要求要建张表TESTTB,里面两个字段(I_ID,I_NAME)。
二:有返回值的存储过程(非列表)
存储过程为:
CREATE OR REPLACE PROCEDURE TESTB(PARA1 IN VARCHAR2,PARA2 OUT VARCHAR2) AS
BEGIN
SELECT INTO PARA2 FROM TESTTB WHERE I_ID= PARA1;
END TESTB;
在java里调用时就用下面的代码:
package com.hyq.src;
public class TestProcedureTWO {
public TestProcedureTWO() {
}
public static void main(String[] args ){
String driver = "oracle.jdbc.driver.OracleDriver";
String strUrl = "jdbc:oracle:thin:@127.0.0.1:1521:hyq";
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(strUrl, " hyq ", " hyq ");
CallableStatement proc = null;
proc = conn.prepareCall("{ call HYQ.TESTB(?,?) }");
proc.setString(1, "100");
proc.registerOutParameter(2, Types.VARCHAR);
proc.execute();
String testPrint = proc.getString(2);
System.out.println("=testPrint=is="+testPrint);
}
catch (SQLException ex2) {
ex2.printStackTrace();
}
catch (Exception ex2) {
ex2.printStackTrace();
}
finally{
try {
if(rs != null){
rs.close();
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
}
}
catch (SQLException ex1) {
}
}
}
}
}
注意,这里的proc.getString(2)中的数值2并非任意的,而是和存储过程中的out列对应的,如果out是在第一个位置,那就是proc.getString(1),如果是第三个位置,就是proc.getString(3),当然也可以同时有多个返回值,那就是再多加几个out参数了。
三:返回列表
由于oracle存储过程没有返回值,它的所有返回值都是通过out参数来替代的,列表同样也不例外,但由于是集合,所以不能用一般的参数,必须要用pagkage了.所以要分两部分,
1, 建一个程序包。如下:
CREATE OR REPLACE PACKAGE TESTPACKAGE AS
TYPE Test_CURSOR IS REF CURSOR;
end TESTPACKAGE;
2,建立存储过程,存储过程为:
CREATE OR REPLACE PROCEDURE TESTC(p_CURSOR out TESTPACKAGE.Test_CURSOR) IS
BEGIN
OPEN p_CURSOR FOR SELECT * FROM HYQ.TESTTB;
END TESTC;
可以看到,它是把游标(可以理解为一个指针),作为一个out 参数来返回值的。
在java里调用时就用下面的代码:
package com.hyq.src;
import java.sql.*;
import java.io.OutputStream;
import java.io.Writer;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import oracle.jdbc.driver.*;
public class TestProcedureTHREE {
public TestProcedureTHREE() {
}
public static void main(String[] args ){
String driver = "oracle.jdbc.driver.OracleDriver";
String strUrl = "jdbc:oracle:thin:@127.0.0.1:1521:hyq";
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(strUrl, "hyq", "hyq");
CallableStatement proc = null;
proc = conn.prepareCall("{ call hyq.testc(?) }");
proc.registerOutParameter(1,oracle.jdbc.OracleTypes.CURSOR);
proc.execute();
rs = (ResultSet)proc.getObject(1);
while(rs.next())
{
System.out.println("<tr><td>" + rs.getString(1) + "</td><td>"+rs.getString(2)+"</td></tr>");
}
}
catch (SQLException ex2) {
ex2.printStackTrace();
}
catch (Exception ex2) {
ex2.printStackTrace();
}
finally{
try {
if(rs != null){
rs.close();
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
}
}
catch (SQLException ex1) {
}
}
}
}
在这里要注意,在执行前一定要先把oracle的驱动包放到class路径里,否则会报错的。
-----------------------------------------------------------------------------------------------------
这是总结以前使用spring调用Oracle存储过程,并用cursor返回结果集的一个完整实例,希望能对大家有帮助。
1. 创建表:
- create table TEST_USERS
- (
- USER_ID VARCHAR2(10) not null,
- NAME VARCHAR2(10) not null,
- PASSWORD VARCHAR2(20) not null
- )
2. 创建存储过程:
- create or replace package display_users_package is
- type search_results is ref cursor;
- procedure display_users_proc(results_out out search_results, userId in test_users.user_id%type);
- end display_users_package;
- create or replace package body display_users_package is
- procedure display_users_proc(results_out out search_results, userId in test_users.user_id%type)
- is
- begin
- if userId is not null then
- open results_out for select * from test_users where user_id like userId || '%';
- else
- open results_out for select * from test_users;
- end if;
- end display_users_proc;
- end display_users_package;
这个results_out是一个游标类型,用来返回查找的结果集。
3. 完整实现代码:
- import java.sql.CallableStatement;
- import java.sql.Connection;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import javax.sql.DataSource;
- import oracle.jdbc.OracleTypes;
- import org.springframework.dao.DataAccessException;
- import org.springframework.jdbc.core.CallableStatementCallback;
- import org.springframework.jdbc.core.CallableStatementCreator;
- import org.springframework.jdbc.core.JdbcTemplate;
- import com.spring.stored.procedure.util.DataContextUtil;
- /**
- * @author Jane Jiao
- *
- */
- public class SpringStoredProce {
- public List<Map> execute(String storedProc, String params){
- List<Map> resultList = null;
- try{
- final DataSource ds = DataContextUtil.getInstance().getDataSource();
- final JdbcTemplate template = new JdbcTemplate(ds);
- resultList = (List<Map>)template.execute(new ProcCallableStatementCreator(storedProc, params),
- new ProcCallableStatementCallback());
- }catch(DataAccessException e){
- throw new RuntimeException("execute method error : DataAccessException " + e.getMessage());
- }
- return resultList;
- }
- /**
- * Create a callable statement in this connection.
- */
- private class ProcCallableStatementCreator implements CallableStatementCreator {
- private String storedProc;
- private String params;
- /**
- * Constructs a callable statement.
- * @param storedProc The stored procedure's name.
- * @param params Input parameters.
- * @param outResultCount count of output result set.
- */
- public ProcCallableStatementCreator(String storedProc, String params) {
- this.params = params;
- this.storedProc = storedProc;
- }
- /**
- * Returns a callable statement
- * @param conn Connection to use to create statement
- * @return cs A callable statement
- */
- public CallableStatement createCallableStatement(Connection conn) {
- StringBuffer storedProcName = new StringBuffer("call ");
- storedProcName.append(storedProc + "(");
- //set output parameters
- storedProcName.append("?");
- storedProcName.append(", ");
- //set input parameters
- storedProcName.append("?");
- storedProcName.append(")");
- CallableStatement cs = null;
- try {
- // set the first parameter is OracleTyep.CURSOR for oracel stored procedure
- cs = conn.prepareCall(storedProcName.toString());
- cs.registerOutParameter (1, OracleTypes.CURSOR);
- // set the sencond paramter
- cs.setObject(2, params);
- } catch (SQLException e) {
- throw new RuntimeException("createCallableStatement method Error : SQLException " + e.getMessage());
- }
- return cs;
- }
- }
- /**
- *
- * The ProcCallableStatementCallback return a result object,
- * for example a collection of domain objects.
- *
- */
- private class ProcCallableStatementCallback implements CallableStatementCallback {
- /**
- * Constructs a ProcCallableStatementCallback.
- */
- public ProcCallableStatementCallback() {
- }
- /**
- * Returns a List(Map) collection.
- * @param cs object that can create a CallableStatement given a Connection
- * @return resultsList a result object returned by the action, or null
- */
- public Object doInCallableStatement(CallableStatement cs){
- List<Map> resultsMap = new ArrayList<Map>();
- try {
- cs.execute();
- ResultSet rs = (ResultSet) cs.getObject(1);
- while (rs.next()) {
- Map<String, String> rowMap = new HashMap<String, String>();
- rowMap.put("userId", rs.getString("USER_ID"));
- rowMap.put("name", rs.getString("NAME"));
- rowMap.put("password", rs.getString("PASSWORD"));
- resultsMap.add(rowMap);
- }
- rs.close();
- }catch(SQLException e) {
- throw new RuntimeException("doInCallableStatement method error : SQLException " + e.getMessage());
- }
- return resultsMap;
- }
- }
- }
- ------------------------------------------------------------------------------
-
内容或简介:
/**
调用数据库里的一个函数
一个函数本质上一个返回一个结果的存储过程,这个例子示范了怎么调用有in、out和in/out参数的函数
***********************************/
CallableStatement cs;
try {
// 调用一个没有参数的函数; 函数返回 a VARCHAR
// 预处理callable语句cs = connection.prepareCall("{? = call myfunc}");
// 注册返回值类型
cs.registerOutParameter(1, i);// Execute and retrieve the returned value
cs.execute();
String retValue = cs.getString(1);// 调用有一个in参数的函数; the function returns a VARCHAR
cs = connection.prepareCall("{? = call myfuncin(?)}");// Register the type of the return value
cs.registerOutParameter(1, Types.VARCHAR);// Set the value for the IN parameter
cs.setString(2, "a string");// Execute and retrieve the returned value
cs.execute();
retValue = cs.getString(1);// 调用有一个out参数的函数; the function returns a VARCHAR
cs = connection.prepareCall("{? = call myfuncout(?)}");// Register the types of the return value and OUT parameter
cs.registerOutParameter(1, Types.VARCHAR);
cs.registerOutParameter(2, Types.VARCHAR);// Execute and retrieve the returned values
cs.execute();
retValue = cs.getString(1); // return value
String outParam = cs.getString(2); // OUT parameter// 调用有一个in/out参数的函数; the function returns a VARCHAR
cs = connection.prepareCall("{? = call myfuncinout(?)}");// Register the types of the return value and OUT parameter
cs.registerOutParameter(1, Types.VARCHAR);
cs.registerOutParameter(2, Types.VARCHAR);// Set the value for the IN/OUT parameter
cs.setString(2, "a string");// Execute and retrieve the returned values
cs.execute();
retValue = cs.getString(1); // return value
outParam = cs.getString(2); // IN/OUT parameter
} catch (SQLException e) {
}