2012-11-08 40 views
0

我已經保存表示爲一個ByteArrayOutputStream到表中的Blob SQL領域的pdf文件,這裏是我的代碼:的Java插入斑點爲ByteArrayOutputStream得到ClassCastException異常

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

但我得到的java.lang。 ClassCastException:

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

我該如何管理?由於

回答

2

有一個setBlob接受一個InputStream,所以

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

你不能投ByteArrayOutputStreamBlob。嘗試創建,如下Blob實例:

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

然後

statement.setBlob(2, blob);