/* * This program operates on the table Cars(name,image) * where name is a string and image is a blob. * * usage: java WriteBlob car-name image-file-name * */ // You need to import the java.sql package to use JDBC import oracle.sql.*; import oracle.jdbc.driver.*; import java.sql.*; import java.io.*; class WriteBlob { public static void main(String[] args) throws SQLException { if(args.length<2){ System.out.println("usage: java WriteBlob name filename"); System.exit(1); } String stname = args[0]; String fname = args[1]; // Load the Oracle JDBC driver DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); // Connect to the database // You can put a database name after the @ sign in the connection URL. Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@occs:1521:occs", "alice", "tiger"); conn.setAutoCommit(false); // If the student is not already in the database add him/her PreparedStatement stmt = conn.prepareStatement("insert into cars "+ "values(?,empty_blob())"); stmt.setString(1,stname); try { stmt.execute(); } catch(SQLException se){ } stmt.close(); // Now, write the image file to the blob field // First, get the student PreparedStatement stmt2 = conn.prepareStatement("select * "+ "from cars "+ "where name = ? "+ "for update"); stmt2.setString(1,stname); ResultSet rset2 = stmt2.executeQuery(); // Then, get the blob BLOB blob = null; if(rset2.next()){ blob = ((OracleResultSet)rset2).getBLOB(2); } // Write from the file to the blob File imageFile = new File(fname); System.out.println(fname +" length = "+imageFile.length()); FileInputStream instream = null; OutputStream outstream = null; try { instream = new FileInputStream(imageFile); blob.truncate(0L); outstream = blob.setBinaryStream(1L); int size = blob.getBufferSize(); System.out.println("buffer size = "+size); byte[] buffer = new byte[size]; int length; while((length = instream.read(buffer))!=-1) outstream.write(buffer,0,length); instream.close(); outstream.close(); } catch (IOException ie){ System.out.println(ie); System.exit(1); } conn.commit(); // Close the Statement stmt.close(); // Close the connection conn.close(); } }