import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class JDBCSelect9 {
	public static void main(String[] args) {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException cnfe) {
			System.err.println("Driver class not found");
			cnfe.printStackTrace();
		}
		Connection con = null;

		try {
			con =
				(Connection) DriverManager.getConnection(
					"jdbc:mysql://localhost/jdbctest/",
					"mario",
					"thePassword");
		} catch (SQLException sqle) {
			System.err.println("Error establishing database connection");
			Throwable t = sqle;
			while (t != null) {
   			System.err.println("Type: " + t.getClass().getName());
      		System.err.println("Message: " + t.getMessage());
      		System.err.println("-----");
      		t = t.getCause();
			}
		}

		try {
			File file = new File(args[0]);
			FileInputStream fis = new FileInputStream(args[0]);
			PreparedStatement pstmt =
				con.prepareStatement(
					"UPDATE EMPLOYEE SET binData =? WHERE  SSN=123456789");
			pstmt.setBinaryStream(1, fis, (int) file.length());
			pstmt.executeUpdate();
			fis.close();

			//read it back from the database
			Statement stmt = (Statement) con.createStatement();
			ResultSet rs =
				stmt.executeQuery(
					"SELECT binData FROM EMPLOYEE WHERE SSN='123456789';");

			FileOutputStream fos = new FileOutputStream(args[1]);
			if (rs.next())
				fos.write(rs.getBytes(1));
			fos.close();

		} catch (SQLException sqle) {
			System.err.println("Error selecting values from table EMPLOYEE");
			Throwable t = sqle;
			while (t != null) {
   			System.err.println("Type: " + t.getClass().getName());
      		System.err.println("Message: " + t.getMessage());
      		System.err.println("-----");
      		t = t.getCause();
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}
