import java.sql.*;

public class DBExample {

    public DBExample() {

	try {
	    //load the database driver - you don't need to instantiate it
	    Class.forName("org.postgresql.Driver");
	}
	catch ( ClassNotFoundException p_e ) {
	    System.err.println("Could not load driver");
	}
    }

    private Connection o_connection;

    void doStuff() {

	try {

	    //get a connection to the database
	    o_connection = DriverManager.getConnection("jdbc:postgresql://db.doc.ic.ac.uk/database","user","password");
	
	    //make a statement and update a table
	    Statement x_stmt = o_connection.createStatement();
	    x_stmt.executeUpdate( "INSERT INTO BOOKS VALUES ( 'Lord of the Rings', 'Tolkein' , 6.99 ) ");

	    //query the database for some data
	    String x_query = "SELECT TITLE, PRICE FROM BOOKS";
	   
	    //loop through the results printing them out
	    for (  ResultSet x_results = x_stmt.executeQuery(x_query); x_results.next() ; ) {

		String x_title = x_results.getString("TITLE");
		float x_price = x_results.getFloat("PRICE");
		System.out.println( x_title + "   " + x_price );
	    }

	}

	catch ( SQLException p_e ) {
	    System.err.println("SQL error : " + p_e.getMessage());
	}

	finally {

	    //always close the connection before returning 

	    try { if ( o_connection != null ) {
		o_connection.close(); 
	    }
	    }
	    catch ( SQLException p_sqle ) {
		System.err.println("Failed to close connection : " + p_sqle.getMessage());	
	    } 
	}
    }

    public static void main( String[] args ) {
	
	new DBExample().doStuff();
    }
}
