/*
 * 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 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 <carname> <filename>");
      System.exit(1);
    }
	
    String carname = args[0];
    String fname = args[1];
    
    try {
      // Connect to the database
      String url = "jdbc:mysql://sql.cs.oberlin.edu/cardb?";
      String parms = "user=alice&password=tiger&useSSL=false";
      Connection conn = DriverManager.getConnection(url+parms);

      // Create a prepared statement
      String fetchStmt = "select image from cars where name = ?";
      PreparedStatement stmt = conn.prepareStatement(fetchStmt);
      stmt.setString(1,carname);

      // Execute the query
      ResultSet rset = stmt.executeQuery();

      Blob blob = null;
      if(rset.next()){
	blob = rset.getBlob("image");
      }
      else {
	System.out.println("Car "+carname+" not found");
	System.exit(1);
      }

      // read blob into byte array
      byte barr[]=new byte[(int)blob.length()];
      barr=blob.getBytes(1,(int)blob.length());

      FileOutputStream outstream = new FileOutputStream(fname);
      outstream.write(barr);
      outstream.close();

      // Close the Statement
      stmt.close();
      // Close the connection
      conn.close();   
    }
    catch (SQLException ie){
      System.out.println(ie);
      System.exit(1);
    }
    catch (IOException ie){
      System.out.println(ie);
      System.exit(1);
    }
  }
}
