Oracle:Java存储函数:使用数据库

时间:2013-09-26 07:10:14

标签: java oracle jdbc stored-functions

我有一个类,它通过JDBC与数据库一起工作。与数据库的连接照常建立:

    Connection conn = null;
    try {
        DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
        conn = DriverManager.getConnection(DS_URL);
    } catch (SQLException ex) {
        logger.debug("Cannot register driver for Oracle DB", ex);
    }

现在我必须使用Oracle数据库存储函数。是否有任何不同的方式来使用DB(例如,通过使用某些上下文建立连接)?对我来说,通过URL在函数内建立连接似乎有些愚蠢,存储在同一个DB中=)

UPD :我有一个在jar中编译的maven项目。我的班级是:

package testjavatooracleproject;

import java.sql.*;

public class App 
{
    public static void main(String[] args) throws SQLException{
        System.out.println(selectJavaObjectById(400094));
    }

    public static String selectJavaObjectById(long id) throws SQLException
    {        
        DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
        Connection conn = DriverManager.getConnection("jdbc:oracle:thin:user/password@localhost:1521:ae");
        PreparedStatement ps = conn.prepareStatement("select * from user_objects where object_id = ?");
        ps.setLong(1, id);
        ResultSet rs = ps.executeQuery();
        int columnCount = rs.getMetaData().getColumnCount();
        StringBuilder sb = new StringBuilder();
        if (rs.next()){
            for(int i = 1; i <= columnCount; i++){
                sb.append(rs.getObject(i));
            }
        }
        conn.close();
        return sb.toString();  
    }
}

接下来,我使用loadjava在DB中上传该jar:

loadjava -resolve -v -user user/password@localhost:1521/ae C:\Exchange\TestJavaToOracleProject.jar

然后我正在尝试创建PL / SQL包装器:

create or replace
function getUserObjectInfoById(obj_id IN NUMBER) return VARCHAR2
as language java 
name 'testjavatooracleproject.App.selectJavaObjectById(long) return java.lang.String';

然后我试图调用我的函数:

select getUserObjectInfoById(400094) from dual;

但是我收到了错误:

ORA-29532: Java call terminated by uncaught Java exception: java.security.AccessControlException: the Permission (java.net.SocketPermission localhost:1521 connect,resolve) has not been granted to user. The PL/SQL to grant this is dbms_java.grant_permission( 'user', 'SYS:java.net.SocketPermission', 'localhost:1521', 'connect,resolve' )
29532. 00000 -  "Java call terminated by uncaught Java exception: %s"
*Cause:    A Java exception or error was signaled and could not be
           resolved by the Java code.
*Action:   Modify Java code, if this behavior is not intended.

UPD :问题解决了。解决方案:使用以下代码创建连接:

OracleDriver ora = new OracleDriver();
Conenction conn = ora.defaultConenction();

2 个答案:

答案 0 :(得分:1)

基本上有三种方法可以注册和加载驱动程序

1. Class.forName(oracle.jdbc.driver.OracleDriver());
   Connection con = DriverManager.getConnection(DS_URL);

2.System.setProperty("jdbc.drivers","sun.jdbc.odbc.JdbcOdbcDriver");

3. as mention by you 

答案 1 :(得分:1)

到目前为止,我记得你得到的错误是因为你没有得到许可

exec dbms_java.grant_permission( 'user', 'SYS:java.net.SocketPermission',
'localhost:1521', 'connect,resolve' );