Вопрос

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

Это было полезно?

Решение

There is a setBlob that takes an InputStream, so

ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
statement.setBlob(2, bais);

Другие советы

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);    
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top