package example; import java.io.*; import java.sql.*; import java.text.*; /** * This example tests the various date styles that are available to postgresql. * * To use this example, you need a database to be in existence. This example * will create a table called datestyle. * */ public class datestyle { Connection db; // The connection to the database Statement st; // Our statement to run queries with // This is our standard to compare results with. java.sql.Date standard; // This is a list of the available date styles including variants. // These have to match what the "set datestyle" statement accepts. String styles[] = { "postgres,european", "postgres,us", "iso", // iso has no variants - us/european has no affect "sql,european", "sql,us", "german" // german has no variants - us/european has no affect }; public datestyle(String args[]) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException { String url = args[0]; String usr = args[1]; String pwd = args[2]; // Load the driver Class.forName("postgresql.Driver"); // Connect to database System.out.println("Connecting to Database URL = " + url); db = DriverManager.getConnection(url, usr, pwd); System.out.println("Connected...Now creating a statement"); st = db.createStatement(); // Clean up the database (in case we failed earlier) then initialise cleanup(); init(); // Now run tests using JDBC methods doexample(); // Clean up the database cleanup(); // Finally close the database System.out.println("Now closing the connection"); st.close(); db.close(); } /** * This drops the table (if it existed). No errors are reported. */ public void cleanup() { try { st.executeUpdate("drop table datestyle"); } catch(Exception ex) { // We ignore any errors here } } /** * This initialises the database for this example */ public void init() throws SQLException { // Create a table holding a single date st.executeUpdate("create table datestyle (dt date)"); // Now create our standard date for the test. // // NB: each component of the date should be different, otherwise the tests // will not be valid. // // NB: January = 0 here // standard = new java.sql.Date(98,0,8); // Now store the result. // // This is an example of how to set a date in a date style independent way. // The only way of doing this is by using a PreparedStatement. // PreparedStatement ps = db.prepareStatement("insert into datestyle values (?)"); ps.setDate(1,standard); ps.executeUpdate(); ps.close(); } /** * This performs the example */ public void doexample() throws SQLException { System.out.println("\nRunning tests:"); for(int i=0;i3) DriverManager.setLogStream(System.err); // Now run the tests try { datestyle test = new datestyle(args); } catch(Exception ex) { System.err.println("Exception caught.\n"+ex); ex.printStackTrace(); } } }