Responding to a customer question about Blob insertion in Oracle 10g DB using the JDBC 3.0 driver. Very Simple application. Download Java Source See insertBlob method.
packagedemo;importjava.sql.*;importjava.io.*;importjava.sql.PreparedStatement;importjava.util.*;importoracle.jdbc.driver.*;importoracle.sql.BLOB;/*** Insert record in the MEDIA table* MEDIA (file_name varchar2(256), file_content BLOB);*/publicclassBlobOracle{privatefinalstaticStringhostname="localhost";privatefinalstaticStringport="1521";privatefinalstaticStringsid="ORCL";privatefinalstaticStringusername="scott";privatefinalstaticStringpassword="tiger";privatestaticStringfileLocation;privatestaticConnectionconnection;publicBlobOracle(){}/** * * @param args */publicstaticvoidmain(String[]args){try{if(args.length==0){System.out.println("\n\n Usage demo.BlobOracle ");System.exit(0);}fileLocation=args[0];setConnection();insertBLOB();}catch(Exceptionex){ex.printStackTrace();}finally{}}privatestaticvoidsetConnection()throwsSQLException{DriverManager.registerDriver(neworacle.jdbc.driver.OracleDriver());connection=DriverManager.getConnection("jdbc:oracle:thin:@"+hostname+":"+port+":"+sid,username,password);connection.setAutoCommit(false);// we must control the commit}privatestaticvoidinsertBLOB()throwsSQLException,Exception{BLOBblob;Filefile;FileInputStreamis;OutputStreamos;longts1=System.currentTimeMillis();//Create a statement.PreparedStatementpstmt=connection.prepareStatement("insert into media (file_name, file_content) values (?,empty_blob())");file=newFile(fileLocation);StringfileName=file.getName();//Set the file name and execute the querypstmt.setString(1,fileName);pstmt.execute();//Take back the record for update (we will insert the blob)//supposely the file name is the PKpstmt=connection.prepareStatement("select file_content from media where file_name = ? for update");pstmt.setString(1,fileName);//Execute the query, and we must have one record so take itResultSetrset=pstmt.executeQuery();rset.next();//Use the OracleDriver resultset, we take the blob locatorblob=((OracleResultSet)rset).getBLOB("file_content");is=newFileInputStream(file);//Create a stream from the file// JDBC 2.0//os = blob.getBinaryOutputStream(); //get the output stream from the Blob to insert it// JDBC 3.0os=blob.setBinaryStream(0);//get the output stream from the Blob to insert it//Read the file by chuncks and insert them in the Blob. The chunk size come from the blobbyte[]chunk=newbyte[blob.getChunkSize()];inti=-1;System.out.println("Inserting the Blob");while((i=is.read(chunk))!=-1){os.write(chunk,0,i);//Write the chunkSystem.out.print('.');// print progression}// When done close the streamsis.close();os.close();//Close the statement and commitpstmt.close();longts2=System.currentTimeMillis();connection.commit();connection.close();System.out.println("\n"+(ts2-ts1)+" ms");}}