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

2 Answers 2

2

There is a setBlob that takes an InputStream, so

ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
statement.setBlob(2, bais);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.