1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| 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;
} |
Partager