/** Returns a table's primary key columns as a Set of strings. */ public static Set<String> getPrimaryKey(DatabaseMetaData metadata, String tableName) throws Exception { Set<String> columns = new HashSet<String>(); ResultSet keys = metadata.getPrimaryKeys( metadata.getConnection().getCatalog(), metadata.getUserName(), tableName); while (keys.next()) { columns.add(keys.getString(PRIMARY_PK_COL_NAME)); } keys.close(); return columns; }
/** Returns a table's columns */ public static List<Column> getColumns(DatabaseMetaData metadata, String tableName) throws Exception { List<Column> columns = new ArrayList<Column>(); PreparedStatement stmt = metadata.getConnection().prepareStatement("SELECT * FROM " + tableName); ResultSetMetaData rsmeta = stmt.getMetaData(); for (int i = 1, ii = rsmeta.getColumnCount(); i <= ii; ++i) { columns.add(new Column(rsmeta, i)); } stmt.close(); return columns; }
/** * Returns a table's foreign keys and their columns as a Map from the key name to the ForeignKey * object. * * <p>A foreign key may not have a name. On such a database, 2 foreign keys must reference 2 * different tables. Otherwise there's no way to tell them apart and the foreign key information * reported by DatabaseMetaData becomes ill-formed. */ public static Map<String, ForeignKey> getForeignKeys(DatabaseMetaData metadata, String tableName) throws Exception { ResultSet keys = metadata.getImportedKeys( metadata.getConnection().getCatalog(), metadata.getUserName(), tableName); Map<String, ForeignKey> map = new HashMap<String, ForeignKey>(); while (keys.next()) { String table = keys.getString(IMPORTED_PK_TAB_NAME); String name = keys.getString(IMPORTED_FK_KEY_NAME); if (name == null || name.length() == 0) name = "UNNAMED_FK_" + table; ForeignKey key = map.get(name); if (key == null) { map.put(name, key = new ForeignKey(table)); } key.add(keys.getString(IMPORTED_FK_COL_NAME)); } keys.close(); return map; }