gpt4 book ai didi

java - 带有 BLOB 参数的 Oracle 存储过程

转载 作者:行者123 更新时间:2023-11-30 11:26:28 26 4
gpt4 key购买 nike

您好,我是使用这项技术 (Oracle SP) 的新手,所以我遇到了一些问题,

具体来说,我想在存储过程上插入一个 BLOB 对象,目前我使用 spring、jboss、java 和 oracle,我的 SP 比 :

PROCEDURE SAVE_DATA(data IN BLOB, date IN DATE) IS
next_id number;
BEGIN
select s_id.nextval into next_id from dual;

INSERT INTO DATA_TABLE( id, data , date)
values
(next_id, data , date);
COMMIT;

EXCEPTION
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20101,''||SQLCODE ||'-'||SUBSTR(SQLERRM,1,500));
END SAVE_FAILED_EMAIL;

所以在 java 方面,我做这样的事情:

  WrappedConnection wrappedCon = (WrappedConnection) this.getDataSource().getConnection();
con = (OracleConnection) wrappedCon.getUnderlyingConnection();
byte[] bytes= IOUtils.toByteArray(input);
blobObj=con.createBlob(bytes);

execute(new CallableStatementCreator() {

public CallableStatement createCallableStatement(Connection con)
throws SQLException {
String procedure = "call SAVE_DATA(?,?)";

CallableStatement stm=con.prepareCall(procedure);

stm.setBlob(1, blobObj);
stm.setDate(2, date);
return stm;
}
}, new CallableStatementCallback<Map<Integer,Object>>() {

public Map<Integer, Object> doInCallableStatement(CallableStatement cs)
throws SQLException,DataAccessException {
cs.execute();
return null;
}}
);
con.commit();
con.close();

但是当我运行这部分代码时,我得到了来自数据库端的下一个异常“ORA-22927 指定的 LOB 定位器无效”

最佳答案

这个有点棘手。您在这里遇到的第一个问题是 Oracle 需要专有的 BLOB 和 CLOB 实例;这是来自 Spring OracleLobHandler 的 javadoc :

While most databases are able to work with DefaultLobHandler, Oracle 9i (or more specifically, the Oracle 9i JDBC driver) just accepts Blob/Clob instances created via its own proprietary BLOB/CLOB API, and additionally doesn't accept large streams for PreparedStatement's corresponding setter methods.

但是当您在 JBoss 中工作时,您还需要一个 NativeJdbcExtractor所以 Spring 可以从 JBoss thread pool wrapper 解开底层连接然后将 lob 插入到 Spring JdbcTemplate 中。

因此,这是您需要更改的代码:

// ...
final byte[] bytes= IOUtils.toByteArray(input);

final OracleLobHandler lobHandler = new OracleLobHandler();
final lobHandler.setNativeJdbcExtractor(new JBossNativeJdbcExtractor());
// ...
new CallableStatementCreator() {

public CallableStatement createCallableStatement(Connection con)
throws SQLException {
String procedure = "call SAVE_DATA(?,?)";

CallableStatement stm=con.prepareCall(procedure);

lobHandler.getLobCreator().setLobAsBytes(smt, 1, bytes, bytes.length);
stm.setDate(2, date);
return stm;
}
}
// ...

关于java - 带有 BLOB 参数的 Oracle 存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19801106/

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