0

I've to save a pdf file represented as a ByteArrayOutputStream into a Blob SQL field of a table, here's my code:

public boolean savePDF(int version, ByteArrayOutputStream baos) throws Exception{
    boolean completed = false;
    ConnectionManager conn = new ConnectionManager();
    try {
        PreparedStatement statement = conn.getConnection().prepareStatement(INSERT_PDF);
        statement.setLong(1, version);
        statement.setBlob(2, (Blob)baos);           
        statement.execute();
        conn.commit();
        completed = true;
    } catch (SQLException e) {
        conn.rollbackQuietly();
        e.printStackTrace();
        throw e;
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }finally{
        conn.close();
    }                           
    return completed;       
}

But I get a java.lang.ClassCastException:

java.io.ByteArrayOutputStream cannot be cast to java.sql.Blob

How can I manage that? Thanks

Fseee
  • 2,476
  • 9
  • 40
  • 63

2 Answers2

2

There is a setBlob that takes an InputStream, so

ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
statement.setBlob(2, bais);
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
2

You can't cast ByteArrayOutputStream to Blob. Try creating the Blob instance as below:

  SerialBlob blob = new SerialBlob(baos.toByteArray());

and then

  statement.setBlob(2, blob);    
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73