Tuesday, July 5, 2011

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();

No comments:

Post a Comment

Chitika