Saturday, November 10, 2007

Blob and Clob Objects:JAVA

Retrieving BLOB and CLOB Values

The binary large object (BLOB) and character large object (CLOB) data types are
treated similarly to the more primitive built-in types. Values of these types can be
retrieved by calling the getBlob and getClob methods in the ResultSet and
CallableStatement interfaces. For example, CODE EXAMPLE 16-1 retrieves a BLOB
value from the first column of the ResultSet rsand a CLOB value from the second
column.

Blob blob = rs.getBlob(1);
Clob clob = rs.getClob(2);

CODE EXAMPLE Retrieving BLOB and CLOB values

The Blob interface contains operations for returning the length of the BLOB value, a
specific range of bytes contained in the BLOB value, and so on. The Clob interface
contains corresponding operations that are character based. The API documentation
gives more details.

An application does not deal directly with the LOCATOR(blob) and
LOCATOR(clob) types that are defined in SQL. By default, a JDBC driver should
implement the Blob and Clob interfaces using the appropriate locator type. Also by
default, Blob and Clob objects remain valid only during the transaction in which
they are created.

Storing Blob and Clob Objects

A Blob or Clob object can be passed as an input parameter to a
PreparedStatement object just like other data types. The method setBlob sets a
PreparedStatement parameter with a Blob object, and the method setClob sets
a Clob object as a parameter. In CODE EXAMPLE authorImageis an instance of
java.sql.Blob retrieved from another SQL statement, and authorBio is a an
instance of java.sql.Clob retrieved from another SQL statement.

PreparedStatement pstmt = conn.prepareStatement(
“INSERT INTO bio (image, text) VALUES (?, ?)");
pstmt.setBlob(1, authorImage);
pstmt.setClob(2, authorBio);

CODE EXAMPLE Setting Blob and Clob objects as parameters to a
PreparedStatement object
The setBinaryStream and setObject methods may also be used to set a Blob
object as a parameter in a PreparedStatement object. The setAsciiStream,
setCharacterStream, and setObject methods are alternate means of setting a
Clob object as a parameter.
The updateBlob and updateClob methods can be used to update a column value
in an updatable result set.

The Blob and Clob interfaces provide methods to alter their internal content. In
CODE EXAMPLE 16-3, the method setBytes is used to write the first five bytes of the
Blob object retrieved from the column DATA.

byte[] val = {0,1,2,3,4};
...
Blob data = rs.getBlob(“DATA”);
int numWritten = data.setBytes(1, val);

CODE EXAMPLE Writing bytes to a Blob object

Similarly, the Clob methods setString and truncate can be used to change the
value of a column containing a Clob object.

No comments: