import java.sql.*;

public class JDBCExample {
	public static void main(String[] argv) {
		// Checking if Driver is registered with DriverManager
		try {
			Class.forName("org.postgresql.Driver");
		} catch (ClassNotFoundException cnfe) {
			System.out.println("Couldn't find the driver!");
			System.out.println("Let's print a stack trace, and exit.");
			cnfe.printStackTrace();
			System.exit(1);
		}
	
		System.out.println("Registered the driver ok.");
	
		// make a connection to PostgreSQL Server
		Connection c = null;
		try {
			// The first argument specifies the location and name of the database to open
			// The second and third arguments are the user name and password,
			// respectively. They should be whatever is necessary to connect
			// to the database.
			c = DriverManager.getConnection("jdbc:postgresql://localhost/mydb", "postgres", "postgres");
		} catch (SQLException se) {
			System.out.println("Couldn't connect: print out a stack trace and exit.");
			se.printStackTrace();
			System.exit(1);
		}
		
		if (c != null)
			System.out.println("Connected to the database.");
		else
			System.out.println("We should never get here.");
		
		// create a statement and result set objects 
		Statement s = null;
		
		try {
			s = c.createStatement();
		} catch (SQLException se) {
			System.out.println("We got an exception while creating a statement:" +
				"that probably means we're no longer connected.");
			se.printStackTrace();
			System.exit(1);
		}		
		ResultSet rs = null;
		
		// execute a SQL statement and store the result in the result set object
		try {
			rs = s.executeQuery("SELECT aid, aname, ctname FROM games.athlete, games.country where dob < '1980-01-01' AND games.athlete.noc = games.country.noc");
			System.out.println("Query executed successfully.");
		} catch (SQLException se) {
			System.out.println("We got an exception while executing our query:" +
				"that probably means our SQL is invalid");
			se.printStackTrace();
			System.exit(1);
		}
		
		// do something with the result which is a relation consists of a set of tuples
		// each tuple consists of an array of values
		int index = 0;
		System.out.println("\nHere are the result of the query:\n");		
		try {
			System.out.println("ID	Name			Country");
			System.out.println("=========================================");
			while (rs.next()) {
				// print out the first three values from the current tuple
				System.out.println(rs.getString(1) + "	" + rs.getString(2) + " " + rs.getString(3));
			}
		} catch (SQLException se) {
			System.out.println("We got an exception while getting a result:this " +
				"shouldn't happen: we've done something really bad.");
			se.printStackTrace();
			System.exit(1);
		}
	}
}