Traverse schema model

This example demonstrates traversing the schema model of a JDBC database connection:

Connection con = ...

DataContext dataContext = DataContextFactory.createJdbcDataContext(con);
Schema[] schemas = dataContext.getSchemas();

// iterate through schemas
for (Schema schema : schemas) {
  
  System.out.println(schema.getName());
  Table[] tables = schema.getTables();
  
  // iterate through tables
  for (Table table : tables) {
    
    System.out.println("  " + table.getName() + " (" + table.getType() + ")");
    Column[] columns = table.getColumns();
    
    // iterate through columns
    for (Column column : columns) {
    
        System.out.println("    " + column.getName() + " (" + column.getType() + "|" + column.getNativeType() + ")");
    }
  }
  
}

Run on an example PostgreSQL database this will print out:

information_schema
pg_catalog
pg_toast_temp_1
public
  person (TABLE)
    id (INTEGER|serial)
    name (VARCHAR|text)
    age (INTEGER|integer)
    company_id (INTEGER|int4)
  company (TABLE)
    id (INTEGER|serial)
    name (VARCHAR|text)
  employments (VIEW)
    employee_name (VARCHAR|text)
    company_name (VARCHAR|text)