/* * This program operates on the table Cars(name,image) * where name is a string and image is a blob. * * usage: java ReadBlob car-name image-file-name * * The image field for the given car is read from * the database and written to the image file * */ // 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 ReadBlob { public static void main(String[] args) throws SQLException { if(args.length<2){ System.out.println("usage: java ReadBlob 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.cs.oberlin.edu:1521:occs", "alice", "tiger"); conn.setAutoCommit(false); PreparedStatement stmt = conn.prepareStatement("select * "+ "from cars "+ "where name = ? "+ "for update"); stmt.setString(1,stname); ResultSet rset = stmt.executeQuery(); BLOB blob = null; if(rset.next()){ blob = ((OracleResultSet)rset).getBLOB(2); } else { System.out.println("Student "+stname+" not found"); System.exit(1); } File imageFile = new File(fname); InputStream instream = null; FileOutputStream outstream = null; try { outstream = new FileOutputStream(imageFile); instream = blob.getBinaryStream(); int size = blob.getBufferSize(); 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(); } }