在Java程序中调用PL / SQL包代码

时间:2014-10-22 15:33:06

标签: java oracle jdbc plsql package

我正在尝试调用PL/SQL程序中使用Java包定义的程序。

我知道可以在Jdbc中使用connection.prepareCall调用存储过程。但是关于如何在程序包中调用过程的信息非常少。

我正处于开发阶段,我仍在考虑使用什么数据库框架。 只是想知道在PLSQL中使用JDBC的优缺点是什么?对于这个用例,有更好的JDBC替代方法吗?

1 个答案:

答案 0 :(得分:7)

按照以下简单步骤操作:

public static final String SOME_NAME = "{call   schema_name.org_name_pkg.return_something(?,?)}"; // Change the schema name,packagename,and procedure name.

// Simple JDBC Connection Pooling
// Here I am passing param companyId which is IN param to stored procedure which will return me some value.

Connection conn = null;
CallableStatement stmt = null;
ResultSet rset = null;

try {
        conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");
        stmt = conn.prepareCall(SOME_NAME);//We have declared this at the very top
        stmt.setString(1, companyid);//Passing CompanyID here
        stmt.registerOutParameter(2, OracleTypes.CURSOR);//Refcursor selects the row based upon query results provided in Package.
        stmt.execute();
        rset = (ResultSet) stmt.getObject(2);

        while (rset.next()) {
            String orgId=rset.getString("RPT_ORG_ID"); 
            // When using refcursor easy to get the value just by using Column name     
            String orgName=rset.getString("RPT_ORG_NAME");    
            // Some Logic based what do you want to do with the data returned back from query
} catch (Exception e) {
        LOGGER.error("Error extracting ", e);
} finally {
        DBUtils.cleanUp(conn, stmt, rset);
}

// Clean and close you connection