/*
 * 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 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 cname = args[0];
    String fname = args[1];
    
    // Get the user's name and password
    java.io.Console cons = System.console();
    cons.printf("Enter username: ");
    String uname = cons.readLine();
    cons.printf("Enter password: ");
    char[] pword = cons.readPassword();
    String pwd = "";
    for(char c : pword)
      pwd += c;
    
    try {
      // Connect to the database
      // You can put a database name after the @ sign in the connection URL.
      String url = "jdbc:mysql://sql.cs.oberlin.edu/cardb?";
      String parms = "user="+uname+"&password="+pwd+"&useSSL=false";
	
      // Connect to the database
      // You can put a database name after the @ sign in the connection URL.
      Connection conn = DriverManager.getConnection (url+parms);
      
      conn.setAutoCommit(false);
      
      // create the insert statement as a string
      String insertStmt = "insert into cars values(?,?)";

      // create a prepared statement
      PreparedStatement stmt = conn.prepareStatement(insertStmt);

      // open the file
      File file = new File(fname);
      FileInputStream input = new FileInputStream(file);

      // fill in the parameters
      stmt.setString(1,cname);
      stmt.setBinaryStream(2,input);

      // store the resume file in database
      System.out.println("Reading file " + file.getAbsolutePath());
      System.out.println("Store file in the database.");
      stmt.executeUpdate();
      stmt.close();

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