/* To enable JDBC programs to work, follow these steps if you haven't already:

   1. make a directory, inside your home directory, called "jdbc"
   2. copy the following file, available from the course website, 
      to the directory you just made:
        mysql-connector-java-3.0.6-stable-bin.jar
   3. open the file ".bashrc" in your home directory with an editor 
      such as emacs (that file may be hidden)
   4. add the following two lines the file .bashrc (anywhere in the file):
      (change "username" to your own username)
        MYSQLDRV="mysql-connector-java-3.0.6-stable-bin.jar"
        export CLASSPATH="/home/username/jdbc/$MYSQLDRV:."
   5. save the file .bashrc
   6. from a command prompt, type "source .bashrc"

   You only need to do this once. From that point on, programs such as the
   following should work properly.

 */

import java.sql.*;

public class JDBCExample {

    public static void main(String[] args) {

	/* change the values of these four Strings */
	String username = "your username";
	String MySQLpassword = "your MySQL password";
	String tablename = "a table in your database";
	String fieldname = "a field in that table";
	
	/* you should be able to leave the rest alone */

	String url = "jdbc:mysql://dbserver.cs.uchicago.edu/" + username;
    	String query = "SELECT " + fieldname + " FROM " + tablename + ";";
	
	try {
	    Class.forName("com.mysql.jdbc.Driver");
	    Connection con = DriverManager.getConnection 
		(url, username, MySQLpassword);
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(query);
	    System.out.println("The contents of field " + fieldname + ":");
	    while (rs.next()) {
		System.out.print(rs.getString(1) + ", ");
	    }
	    System.out.println();
            rs.close();
            stmt.close();
            con.close();

	} catch (Exception e) {
	    System.out.println(e);
	}
    }
}
