gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:42:21 25 4
gpt4 key购买 nike

我有一个类,它通过 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 存储函数。是否有任何不同的方式来使用数据库(例如通过使用某些上下文建立连接)?对我来说,通过函数内部的 URL 建立连接似乎有点愚蠢,该连接存储在同一个数据库中 =)

UPD:我有在 jar 中编译的 Maven 项目。我的类(class)是:

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 将该 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();

最佳答案

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

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

关于java - Oracle:Java 存储函数:使用数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19021638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com