microacup / microacup.github.com

长者的经验
0 stars 1 forks source link

JDBC调用存储过程 #20

Open microacup opened 11 years ago

microacup commented 11 years ago

图表支持存储过程,需要调用已存在于oracle中的存储过程。附上最简单的java调用带参数的存储过程,其中:第一个参数in参数,第二个参数out参数是游标SYS_REFCURSOR 存储过程实例:

CREATE OR REPLACE PROCEDURE "SEARCHNAME"
(icode in char, P_RESULT_SET OUT SYS_REFCURSOR)
AS
BEGIN
        OPEN P_RESULT_SET FOR
        SELECT * FROM TEST_PROCE WHERE TEST_PROCE.CODE = icode;        
END;

java代码:

package test;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

public class Test {

    public static void main(String[] args) {
        String url = "jdbc:oracle:thin:@10.2.4.169:1521:orcl";
        Connection conn = null;
        CallableStatement proc = null;

        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = DriverManager.getConnection(url,"GIS","GIS");
            proc = conn.prepareCall("{ call searchname(?,?) }"); // 执行存储过程searchname
            proc.setString(1, "1002"); // 设置参数in
            proc.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR); // 注册游标
            proc.execute(); // 执行

            ResultSet rs = (ResultSet) proc.getObject(2); //取得结果集
            ResultSetMetaData rsmd = rs.getMetaData();

            while (rs.next()) {
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    String columnName = rsmd.getColumnName(i);
                    String columnValue = rs.getString(columnName);
                    System.out.println(columnName + ":" + columnValue);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

本例在jdk1.5下测试通过。

关键点: java.sql.CallableStatement;

可自行googlejava.sql.CallableStatement;

microacup commented 11 years ago

扩展 阅读:http://blog.csdn.net/hsuxu/article/details/8782602