问题
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