Showing posts with label blob. Show all posts
Showing posts with label blob. Show all posts

Tuesday, 5 July 2011

JDBC: retrieve values from BLOB or CLOB

There are four pairs of methods in the java.sql.ResultSet class that deal with BLOBs/CLOBs:
  1. Reader getCharacterStream(int columnIndex)   /
    Reader getCharacterStream(String columnName)
  2. InputStream getBinaryStream(int columnIndex)  /
    InputStream getBinaryStream(String columnName)
  3. Blob getBlob(int i)/Blob getBlob(String colName)
  4. Clob getClob(int i)/Clob getClob(String colName)


Example code:
PreparedStatement pstmt = conn.prepareStatement("SELECT image FROM photos where id = ?");
pstmt.setInt(100);
ResultSet rs= pstmt.executeQuery();
while(rs.next()) {
InputStream in = rs.getBinaryStream(1);
...
}
rs.close();

JDBC: insert BLOB or CLOB

Use java.sql.PreparedStatement to insert a BLOB or CLOB field:
  1. void setAsciiStream(int parameterIndex, InputStream x, int length)
    Sets the designated parameter to the given input stream, which will have the specified number of bytes.
  2. void setBinaryStream(int parameterIndex, InputStream x, int length)
    Sets the designated parameter to the given input stream, which will have the specified number of bytes.
  3. void setCharacterStream(int parameterIndex, Reader reader, int length)
    Sets the designated parameter to the given Reader object, which is the given number of characters long.
  4. void setClob(int i, Clob x)
    Sets the designated parameter to the given Clob object.
  5. void setBlob(int i, Blob x)
    Sets the designated parameter to the given Blob object.


Example code:
PreparedStatement pstmt = 
con
.prepareStatement("INSERT INTO photos (id, image) VALUES( ?, ? )");
File inFile = new File("PHOTO12.jpg");
FileInputStream in = new FileInputStream(inFile);
long len = inFile.length();
pstmt.setInt(1, 101);
pstmt.setBinaryStream(2, in, (int)len);
pstmt.executeUpdate();
in.close();