import java.sql.*;

public class DBExtractor extends DataExtractor {
    private String sql;
    private Connection conn;
    private Statement st;
    private ResultSet rec;
    boolean nomorerows = false;

    public DBExtractor() {
	try {
	    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
	    String url = "jdbc:odbc:students";
	    conn = DriverManager.getConnection(url, "", "");
	}
	catch (ClassNotFoundException e) {
	    System.out.println("Driver class not found");
	    System.out.println(e.getMessage());
	}
	catch (SQLException e) {
	    System.out.println("Database URL is invalid");
	    System.out.println(e.getMessage());
	}
    }

    public void initialize() {
	try {
	    st = conn.createStatement();
	}
	catch (SQLException e) {
	    System.out.println("Could not create statement\n" +
			       e.getMessage());
	}
    }

    public void startExtraction() {
	nomorerows = false;
	sql = "select firstname, lastname from Student";
	try {
	    rec = st.executeQuery(sql);
	}
	catch (SQLException e) {
	    System.out.println("Could not execute query\n" +
			       e.getMessage());
	}
    }

    public Object getNextRow() {
	try {
	    if (rec.next()) 
		return new Student(rec.getString("firstname"),
				   rec.getString("lastname"));
	    else {
		nomorerows = true;
		return null;
	    }
	}
	catch (SQLException e) {
	    System.out.println("Could not get next row\n" +
			       e.getMessage());
	}
	return null;
    }

    public boolean finished() {
	return nomorerows;
    }

    public void endExtraction() {
	try {
	    rec.close();
	}
	catch (SQLException e) {
	    System.out.println("Could not close dataset \n" +
			       e.getMessage());
	}
    }
}

