gpt4 book ai didi

java - 过于复杂的 oracle jdbc BLOB 处理

转载 作者:IT老高 更新时间:2023-10-28 21:03:39 25 4
gpt4 key购买 nike

当我在网上搜索使用 jdbc 瘦驱动程序将 BLOB 插入 Oracle 数据库时,大多数网页都建议采用 3 步方法:

  1. 插入 empty_blob() 值。
  2. 选择带有进行更新的行。
  3. 插入实际值。

这对我来说很好,这是一个例子:

Connection oracleConnection = ...

byte[] testArray = ...

PreparedStatement ps = oracleConnection.prepareStatement(
"insert into test (id, blobfield) values(?, empty_blob())");
ps.setInt(1, 100);
ps.executeUpdate();
ps.close();
ps = oracleConnection.prepareStatement(
"select blobfield from test where id = ? for update");
ps.setInt(1, 100);
OracleResultSet rs = (OracleResultSet) ps.executeQuery();
if (rs.next()) {
BLOB blob = (BLOB) rs.getBLOB(1);
OutputStream outputStream = blob.setBinaryStream(0L);
InputStream inputStream = new ByteArrayInputStream(testArray);
byte[] buffer = new byte[blob.getBufferSize()];
int byteread = 0;
while ((byteread = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, byteread);
}
outputStream.close();
inputStream.close();
}

在一些网页中,作者建议使用更简单的 1 步解决方案。此解决方案的上一个示例:

Connection oracleConnection = ...

byte[] testArray = ...

PreparedStatement ps = oracleConnection.prepareStatement(
"insert into test(id, blobfield) values(?, ?)");
BLOB blob = BLOB.createTemporary(oracleConnection, false, BLOB.DURATION_SESSION);
OutputStream outputStream = blob.setBinaryStream(0L);
InputStream inputStream = new ByteArrayInputStream(testArray);
byte[] buffer = new byte[blob.getBufferSize()];
int byteread = 0;
while ((byteread = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, byteread);
}
outputStream.close();
inputStream.close();

ps.setInt(1, 100);
ps.setBlob(2, blob);
ps.executeUpdate();
ps.close();

第二个代码更容易,所以我的问题是:第一个(流行的)解决方案有什么意义?第二种解决方案(Oracle 服务器版本号、jdbc 驱动程序版本、blob 大小……)是否存在(是否存在)某种约束?第一个解决方案更好(速度,内存消耗,......)?有什么理由不使用更简单的第二种方法?

同样的问题也适用于 CLOB 字段。

最佳答案

您在第一种情况下提到的更新方法可以使用纯 JDBC 代码重写,从而减少您对 Oracle 特定类的依赖。如果您的应用需要与数据库无关,这可能会有所帮助。

public static void updateBlobColumn(Connection con, String table, String blobColumn, byte[] inputBytes, String idColumn, Long id) throws SQLException {
PreparedStatement pStmt = null;
ResultSet rs = null;
try {
String sql =
" SELECT " + blobColumn +
" FROM " + table +
" WHERE " + idColumn + " = ? " +
" FOR UPDATE";
pStmt = con.prepareStatement(sql,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
pStmt.setLong(1, id);
rs = pStmt.executeQuery();
if (rs.next()) {
Blob blob = rs.getBlob(blobColumn);
blob.truncate(0);
blob.setBytes(1, inputBytes);
rs.updateBlob(blobColumn, blob);
rs.updateRow();
}
}
finally {
if(rs != null) rs.close();
if(pStmt != null) pStmt.close();
}
}

对于 MSSQL,我理解锁定语法是不同的:

String sql = 
" SELECT " + blobColumn +
" FROM " + table + " WITH (rowlock, updlock) " +
" WHERE " + idColumn + " = ? "

关于java - 过于复杂的 oracle jdbc BLOB 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/862355/

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