【问题标题】:How to write / update Oracle blob in a reliable way?如何以可靠的方式编写/更新 Oracle blob?
【发布时间】:2012-01-11 00:23:06
【问题描述】:

我正在尝试在 blob 列中编写和更新 pdf 文档,但我只能更新 blob,仅写入比以前存储的数据更多的数据。 如果我尝试使用较小的文档数据更新 blob 列,我只会得到损坏的 pdf。

首先使用 empty_blob() 函数初始化 blob 列。我在下面编写了示例 Java 类来测试这种行为。我第一次使用 'true' 作为 main 方法的第一个参数运行它,因此在第一行中存储了大约 31kB 的文档,在第二行中存储了 278kB 的文档。 然后我用'false'作为参数运行它,这样两行应该更新交换文档。结果是,只有当我写入的数据比现有数据多时,我才能得到正确的结果。

如何编写一个以可靠方式写入和更新 blob 的方法,而不用担心二进制数据的大小?

import static org.apache.commons.io.IOUtils.copy;

import java.io.FileInputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import oracle.jdbc.OracleDriver;
import oracle.jdbc.OracleResultSet;
import oracle.sql.BLOB;

import org.apache.commons.lang.ArrayUtils;
/**
 * Prerequisites:
 * 1) a table named 'x' must exists [create table x (i number, j blob);] 
 * 2) that table should have two columns [insert into x (i, j) values (1, empty_blob()); insert into x (i, j) values (2, empty_blob()); commit;]
 * 3) download lsp.pdf from http://www.objectmentor.com/resources/articles/lsp.pdf
 * 4) download dotguide.pdf from http://www.graphviz.org/Documentation/dotguide.pdf
 */
public class UpdateBlob {
    public static void main(String[] args) throws Exception {
        processFiles(new String[]{"lsp.pdf", "dotguide.pdf"}, Boolean.valueOf(args[0]));
    }

    public static void processFiles(String [] fileNames, boolean forward) throws Exception {
      if(!forward){
        ArrayUtils.reverse(a);
      }
      int idx = 1;
      for(String fname : fileNames){
        insert(idx++, fname);
      }
  }

    private static void insert(int idx, String fname) throws Exception{
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            DriverManager.registerDriver(new OracleDriver());
            conn = DriverManager.getConnection("jdbc:oracle:thin:@"+db+":"+port+":"+sid, user, pwd);
            ps = conn.prepareStatement("select j from x where i = ? for update");
            ps.setLong(1, idx);

            rs = ps.executeQuery();

            if (rs.next()) {
                FileInputStream instream = new FileInputStream(fname);
                BLOB blob = ((OracleResultSet)rs).getBLOB(1);
                OutputStream outstream = blob.setBinaryStream(1L);
                copy(instream, outstream);
                instream.close();
                outstream.close();
            }
            rs.close();
            ps.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new Exception(e);
        }
    }
}

Oracle 版本:11.1.0.7.0 - 64 位

我什至尝试了标准的 JDBC API 而不使用 Oracle 的特定 API(如上面的示例),但没有任何成功。

【问题讨论】:

  • 也许我遗漏了一些明显的东西......但是copy 方法在哪里定义?我的预感是 copy 方法没有达到您的预期,并且仅在新数据小于旧数据时才替换前 N 个字节。
  • 顺便说一句:你不应该为函数的每次调用打开一个新的连接。那会很慢。
  • @JustinCave copy 方法在 org.apache.commons.io.IOUtils 类中定义。代码开头有一个静态导入。静态导入会降低可读性,但我认为在某些情况下使用它们很方便。
  • @a_horse_with_no_name 上面的代码只是一个非常快速的 POC。我总是使用连接池来管理数据库连接。

标签: java oracle jdbc blob


【解决方案1】:

这要容易得多:

PreparedStatement pstmt =
  conn.prepareStatement("update blob_table set blob = ? where id = ?");
File blob = new File("/path/to/picture.png");
FileInputStream in = new FileInputStream(blob);

// the cast to int is necessary because with JDBC 4 there is 
// also a version of this method with a (int, long) 
// but that is not implemented by Oracle
pstmt.setBinaryStream(1, in, (int)blob.length()); 

pstmt.setInt(2, 42);  // set the PK value
pstmt.executeUpdate();
conn.commit();
pstmt.close();

在使用 INSERT 语句时它的工作方式相同。不需要empty_blob() 和第二个更新声明。

【讨论】:

  • 感谢您的解决方案完美运行(即使正确的setBinaryStream 的签名是(int parameterIndex, InputStream x, int length))。
  • 如果是java对象而不是文件怎么办?
  • Hari:使用 ObjectInputStream 或 ByteArrayInputStream
  • @a_horse_with_no_name 我遇到了同样的问题并尝试实施此解决方案。我应该将PK值设置为什么?是否依赖于数据库?
  • @Zibbobz:你必须知道 PK 值是多少。这可能是一个序列值,或者一个 GUID 或其他东西。你是唯一能回答这个问题的人。
【解决方案2】:

除了a_horse_with_no_name 的answer(依赖于PreparedStatement.setBinaryStream(...) API)之外,至少还有两个用于 BLOB 的选项,还有 3 个用于 CLOB 和 NCLOB 的选项:

  1. 显式创建一个 LOB,写入它,然后使用PreparedStatement.setBlob(int, Blob):

    int insertBlobViaSetBlob(final Connection conn, final String tableName, final int id, final byte value[])
    throws SQLException, IOException {
        try (final PreparedStatement pstmt = conn.prepareStatement(String.format("INSERT INTO %s (ID, VALUE) VALUES (?, ?)", tableName))) {
            final Blob blob = conn.createBlob();
            try (final OutputStream out = new BufferedOutputStream(blob.setBinaryStream(1L))) {
                out.write(value);
            }
    
            pstmt.setInt(1, id);
            pstmt.setBlob(2, blob);
            return pstmt.executeUpdate();
        }
    }
    
  2. 通过SELECT ... FOR UPDATE 更新一个空的LOB(通过DBMS_LOB.EMPTY_BLOB() 或DBMS_LOB.EMPTY_CLOB() 插入)。这是 Oracle 特有的,需要执行两条语句而不是一条。此外,这也是您最初想要实现的目标:

    void insertBlobViaSelectForUpdate(final Connection conn, final String tableName, final int id, final byte value[])
    throws SQLException, IOException {
        try (final PreparedStatement pstmt = conn.prepareStatement(String.format("INSERT INTO %s (ID, VALUE) VALUES (?, EMPTY_BLOB())", tableName))) {
            pstmt.setInt(1, id);
            pstmt.executeUpdate();
        }
    
        try (final PreparedStatement pstmt = conn.prepareStatement(String.format("SELECT VALUE FROM %s WHERE ID = ? FOR UPDATE", tableName))) {
            pstmt.setInt(1, id);
            try (final ResultSet rset = pstmt.executeQuery()) {
                while (rset.next()) {
                    final Blob blob = rset.getBlob(1);
                    try (final OutputStream out = new BufferedOutputStream(blob.setBinaryStream(1L))) {
                        out.write(value);
                    }
                }
            }
        }
    }
    
  3. 对于 CLOB 和 NCLOB,您还可以分别使用 PreparedStatement.setString() 和 setNString()。

【讨论】:

    【解决方案3】:

    FWIW,对于适合内存的东西,我发现我可以简单地将字节数组作为准备好的语句参数传递,而不是通过“流”严谨的士气(或更糟糕的 Oracle 特定/建议的东西)

    使用 Spring “JDBC 模板”包装器(org.springframework.jdbc.core.JdbcTemplate)将“大”(或非)字符串的内容放入 BLOB 列,代码如下所示:

    jdbc.update( "insert into a_table ( clob_col ) values ( ? )", largeStr.getBytes() );
    

    没有第 2 步。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-08
      • 2012-05-08
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多