java insert Blob as ByteArrayOutputStream get ClassCastException

淺唱寂寞╮ 提交于 2020-01-06 12:36:14

问题


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


回答1:


There is a setBlob that takes an InputStream, so

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



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


来源:https://stackoverflow.com/questions/13293828/java-insert-blob-as-bytearrayoutputstream-get-classcastexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!