我有一个类,它通过 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 建立连接似乎有点愚蠢,它存储在同一个数据库中 =)
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 将该 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();