/* * This file defines an object which retrieves data * from a database table cars(name,image) * where name is a string and image is a blob. * * The getCarList method retrieves a list of the * names of all cars in the database. * * The getImage method retrieves a picture of a * car, given the car's name, as an * input stream. */ // You need to import the java.sql package to use JDBC import oracle.sql.*; import oracle.jdbc.driver.*; import java.sql.*; import java.io.*; import java.util.*; class DatabaseAccess { Connection conn; DatabaseAccess() { try { // 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. conn = DriverManager.getConnection ("jdbc:oracle:thin:@occs.cs.oberlin.edu:1521:occs", "alice", "tiger"); conn.setAutoCommit(false); } catch (SQLException e){ System.out.println(e); System.exit(1); } } public List getCarList() { List result = new ArrayList(); try { Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery("select name from cars order by name"); while(rset.next()) result.add(rset.getString(1)); } catch(SQLException e){ System.out.println(e); return result; } return result; } public InputStream getImageStream(String name) { InputStream stream = null; try { Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery("select image from cars "+ "where name = '" + name + "'"); if(rset.next()){ BLOB blob = ((OracleResultSet)rset).getBLOB(1); if(blob!=null) stream = blob.getBinaryStream(); } } catch (SQLException e){ throw new RuntimeException(e.getMessage()); } return stream==null?null:stream; } }