Bonjour, en fait il faut pas gérer cela avec java.sql.Blob mais avec l'implementation faite par oracle. Télécharge le jdbc oracle. Puis tu fais cela:
public static void main(String[] args) throws ClassNotFoundException, SQLException{ String fileName = args.length == 1 ? args[0] : "toto.txt"; Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connexion = DriverManager.getConnection("jdbc:oracle:thin@localhost:1521:mydb","sa",""); PreparedStatement st = connexion.prepareStatement("insert into blobs values(?, ?)"); st.setLong(1, 1l); prepareStatementOracleBlob(st, readFile(fileName), 2); st.execute(); st.close(); connexion.close(); } /** * Set a blob into a OraclePreparedStatement. * @param st The statement instanceof OraclePreparedStatement * @param content The blob content * @param index The index of the blob in the sql expression. * @throws SQLException If an error occurs while setting blob. */ public static void prepareStatementOracleBlob(PreparedStatement st, byte[] content, int index) throws SQLException{ if (content == null) { st.setNull(index, Types.BINARY); } else if (st instanceof oracle.jdbc.OraclePreparedStatement) { oracle.jdbc.OraclePreparedStatement ost = (oracle.jdbc.OraclePreparedStatement) st; oracle.sql.BLOB blob = oracle.sql.BLOB.createTemporary(st .getConnection(), false, oracle.sql.BLOB.DURATION_SESSION);
blob.open(oracle.sql.BLOB.MODE_READWRITE);
OutputStream out = blob.getBinaryOutputStream();
try { out.write((byte[]) content); out.flush(); out.close(); } catch (IOException e) { throw new SQLException("Failed write to blob " + e.getMessage()); } blob.close(); ost.setBLOB( index, blob); } else throw new InvalidParameterException("The prepared statement is not an instance of oracle.jdbc.OraclePreparedStatement, it is a " + st.getClass()); } private static byte[] readFile(String fileName) { byte[] content = new byte[0]; byte[] buffer = new byte[ (int) (5 * Math.pow(2, 20)) ]; // 5 mo int read = 0; BufferedInputStream bi = null; try{ bi = new BufferedInputStream( new FileInputStream( fileName ) ); while( ( read = bi.read( buffer ) ) > 0 ){ byte[] tmp = content; content = new byte[tmp.length + read]; System.arraycopy(tmp, 0, content, 0, tmp.length); System.arraycopy(buffer, 0, content, tmp.length, read); } }catch (Exception e) { e.printStackTrace(); }finally{ try{ if( bi != null ) bi.close(); }catch (Exception e) { e.printStackTrace(); } } return content; }
|