无法使用getImportedKeys()或getExportedKeys()获取外键,仅getPrimaryKeys()有效

时间:2018-06-20 20:01:00

标签: java mysql postgresql jdbc foreign-keys

我无法使用元数据中的getImportedKeys()或getExportedKeys()查找外键。该数据库确实包含外键关系,并且getPrimaryKey()起作用。我该如何解决?

DatabaseMetaData dbMeta = conn.getMetaData();
System.out.println("Foreign Keys are\n");
ResultSet rs = dbMeta.getExportedKeys("", "", "CUSTOMERS");
while (rs.next()) {
    //System.out.println(rs.getString("FKCOLUMN_NAME"));
    System.out.println(rs.getString("FK_NAME") + "\t" + rs.getString("FKCOLUMN_NAME"));
    }

1 个答案:

答案 0 :(得分:0)

尝试一下,看看是否可行:)

private static void printForeignKeys(Connection connection, String CUSTOMERS) throws SQLException {
    System.out.println("Foreign Keys are\n");
    DatabaseMetaData dbMeta= connection.getMetaData();
    ResultSet foreignKeys = dbMeta.getImportedKeys(connection.getCatalog(), null, CUSTOMERS);
    while (foreignKeys.next()) {
        String fkName = foreignKeys.getString("FK_NAME");
        String fkColumnName = foreignKeys.getString("FKCOLUMN_NAME");
        System.out.println(fkName + "." + fkColumnName);
    }
}