将数据附加到 DB2 blob

Append data to a DB2 blob

在我的 DB2 数据库中,我有一个 table 和一个 Blob:

CREATE TABLE FILE_STORAGE (
    FILE_STORAGE_ID integer,
    DATA blob(2147483647),
    CONSTRAINT PK_FILE_STORAGE PRIMARY KEY (FILE_STORAGE_ID));

使用db2jcc JDBC驱动程序(db2jcc4-9.7.jar),我可以在这个table中读写数据没有任何问题。

现在我需要能够向现有行追加数据,但是 DB2 给出了神秘错误

Invalid operation: setBinaryStream is not allowed on a locator or a reference. ERRORCODE=-4474, SQLSTATE=null

我使用以下代码附加我的数据:

String selectQuery = "SELECT DATA FROM FILE_STORAGE WHERE FILE_STORAGE_ID = ?";
try (PreparedStatement ps = conn.prepareStatement(selectQuery, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) {
    ps.setInt(1, fileStorageID);
    try (ResultSet rs = ps.executeQuery()) {
        if (rs.next()) {
            Blob existing = rs.getBlob(1);
            try {
                // The following line throws the exception:
                try (OutputStream output = existing.setBinaryStream(existing.length() + 1)) {
                    // append the new data to the output:
                    writeData(output);
                } catch (IOException e) {
                    throw new IllegalStateException("Error writing output stream to blob", e);
                }

                rs.updateBlob(1, existing);
                rs.updateRow();
            } finally {
                existing.free();
            }
        } else {
            throw new IllegalStateException("No row found for file storage ID: " + fileStorageID);
        }
    }
}

我的代码使用了 OutputStream to the BLOB column of a DB2 database table. There also seem to be other people who have the same problem: Update lob columns using lob locator 中建议的方法。

作为解决方法,我目前将所有现有数据读入内存,将新数据追加到内存中,然后将完整数据写回 blob。这可行,但它非常慢,而且如果 blob 中有更多数据,显然需要更长的时间,每次更新都会变慢。

我确实需要使用 Java 来更新数据,但除了从 JVM 切换之外,我很乐意尝试任何可能的替代方案,我只需要以某种方式附加数据。

提前感谢您的任何想法!

如果您只需要将数据追加到 BLOB 列的末尾并且不想将整个值读入您的程序,一个简单的 UPDATE 语句会更快更直接。

您的 Java 程序可以通过 executeUpdate():

运行 像这样的东西
UPDATE file_storage SET data = data || BLOB(?) WHERE file_storage_id = ?

此参数标记将由 setBlob(1, dataToAppend)setInt(2, fileStorageID) 填充。