/** * Title: PostgreSQL Test
* Description: This project tests PostgreSQL jdbc driver's DatabaseMetaData
* Copyright: Copyright (c) Tom Falconer
* Company:
* @author Tom Falconer * @version 1.0 */ package postgrestest; import java.sql.*; import java.util.*; import java.io.*; public class TestBed { private static final String driverClass = "org.postgresql.Driver"; private static final String url = "jdbc:postgresql://localhost/tomDb"; private Connection connection; private DatabaseMetaData metadata; private PrintWriter printer; private File printFile = new File(System.getProperty("user.home"), "testbed.txt"); public TestBed() throws SQLException, ClassNotFoundException, IOException { Class.forName(driverClass); connection = DriverManager.getConnection(url, "tom", "tom"); metadata = connection.getMetaData(); printer = new PrintWriter(new FileWriter(printFile)); } public void printTest() { try { printer.println("Tables:"); String[] tableTypes = getTableTypes(); dumpResultSet(metadata.getTables(connection.getCatalog(), null, null, tableTypes)); } catch (Exception ex) { ex.printStackTrace(printer); } try { printer.println("Indexes:"); dumpResultSet(metadata.getIndexInfo(connection.getCatalog(), "", "parts", false, false)); } catch (Exception ex) { ex.printStackTrace(printer); } } public String[] getTableTypes() throws SQLException { Vector vector = new Vector(); ResultSet rsTT = metadata.getTableTypes(); while (rsTT.next()) { vector.add(rsTT.getString(1)); } String[] response = new String[vector.size()]; Iterator iter = vector.listIterator(); int i = 0; while (iter.hasNext()) { response[i++] = (String)iter.next(); } return response; } public void close() throws SQLException { printer.println("Closing"); printer.close(); connection.close(); } /** * This method dumps the contents of the resultset onto the standard output. */ public void dumpResultSet(ResultSet rs) throws SQLException { ResultSetMetaData rmd = rs.getMetaData(); int numCols = rmd.getColumnCount(); printer.println("\nDumping ResultSet:"); while (rs.next()) { for (int i = 1; i <= numCols; i++) { printer.println("\tColumn " + i + "\tName: " + rmd.getColumnName(i) + "\tType: " + rmd.getColumnTypeName(i) + "\tValue: " + rs.getString(i)); } printer.println("\n---------\n"); printer.flush(); } rs.close(); printer.println("End of ResultSet\n"); } public static void main(String[] args) { try { TestBed testBed1 = new TestBed(); testBed1.printTest(); testBed1.close(); } catch (Exception ex) { ex.printStackTrace(); } } }