Example: Using BLOBs
This is an example of how to use BLOBs in your Java™ applications.
Note: By using the code examples, you agree to the terms of the Code license and disclaimer information.
/////////////////////////////////////////
// UseBlobs is an example application
// that shows some of the APIs associated
// with Blob objects.
//
// This program must be run after
// the PutGetBlobs program has completed.
/////////////////////////////////////////
import java.sql.*;
public class UseBlobs {
public static void main(String[] args)
throws SQLException
{
// Register the native JDBC driver.
try {
Class.forName("com.ibm.db2.jdbc.app.DB2Driver");
} catch (Exception e) {
System.exit(1); // Setup error.
}
Connection c = DriverManager.getConnection("jdbc:db2:*local");
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM CUJOSQL.BLOBTABLE");
rs.next();
Blob blob1 = rs.getBlob(1);
rs.next();
Blob blob2 = rs.getBlob(1);
// Determine the length of a LOB.
long end = blob1.length();
System.out.println("Blob1 length is " + blob1.length());
// When working with LOBs, all indexing that is related to them
// is 1-based, and is not 0-based like strings and arrays.
long startingPoint = 450;
long endingPoint = 500;
// Obtain part of the BLOB as a byte array.
byte[] outByteArray = blob1.getBytes(startingPoint, (int)endingPoint);
// Find where a sub-BLOB or byte array is first found within a
// BLOB. The setup for this program placed two identical copies of
// a random BLOB into the database. Thus, the start position of the
// byte array extracted from blob1 can be found in the starting
// position in blob2. The exception would be if there were 50
// identical random bytes in the LOBs previously.
long startInBlob2 = blob2.position(outByteArray, 1);
System.out.println("pattern found starting at position " + startInBlob2);
c.close(); // Connection close closes stmt and rs too.
}
}