OutputStream to the BLOB column of a DB2 database

2019-07-19 17:23发布

问题:

In a DB2 database, I have the following table:

CREATE TABLE MyTestTable
( 
    MYPATH VARCHAR(512) NOT NULL, 
    MYDATA BLOB, 
    CONSTRAINT MYTESTTABLE_PK PRIMARY KEY (MYPATH)
);

Using Java, I wish to update an existing row in this table with new blob data. My preferred way is to obtain an OutputStream to the BLOB column & write my data to the OutputStream.

Here is the test code I am using:

Connection connection = null;
PreparedStatement pStmnt = null;
ResultSet rSet = null;

try {
    connection =  ... // get db connection
    String id = ... // set the MYPATH value 

    String sql = "SELECT MYDATA FROM MyTestTable WHERE MYPATH='"+id+"' FOR UPDATE";

    pStmnt = connection.prepareStatement(sql);
    rSet = pStmnt.executeQuery();
    while (rSet.next()) {
        Blob blobData = rSet.getBlob("MYDATA");  // this is a java.sql.Blob

        OutputStream blobOutputStream = blobData.setBinaryStream(1);
        blobOutputStream.write(data);
        blobOutputStream.close();
        connection.commit();
    }
}
// close ResultSet/PreparedStatement/etc in the finally block

The above code works for the Oracle DB.

However, in DB2, calling setBinaryStream to get the OutputStream does not seem to work. The data does not get updated, and I do not get any error messages.

Qs: How can I get an OutputStream to the BLOB column of a DB2 table? What might need to be changed in the above code?

回答1:

You are probably getting the data written to the Blob object successfully, but you need to do more with the PreparedStatement and ResultSet in order to actually update the value in the database.

First, your PreparedStatement must be instantiated using a version of Connection.prepareStatement() that takes a resultSetConcurrency parameter, which you must set to the value ResultSet.CONCUR_UPDATABLE. (I don't know that the SQL SELECT actually needs to specify the FOR UPDATE clause - see the tutorial at the link at the end of this answer.)

Second, after you close blobOutputStream, you need to update the value in the ResultSet using updateBlob(int columnIndex, Blob x) or updateBlob(String columnLabel, Blob x), then invoke ResultSet.updateRow() before doing a Connection.commit().

I haven't updated Blob values this way myself, but it should work. If you run into any issues trying to reuse the Blob originally read from the ResultSet (which you probably don't need to do if you're not actually using the original data), you can use Connect.createBlob() to make an empty one to start with. You can learn more about updating ResultSets from this tutorial.