-3

How to count the number of foreign keys in a SQL database using java. I have been given a database and there are many tables inside that. I have to count the total number of foreign keys present inside id. I am executing the queries via Java.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Prinshu Kumar
  • 33
  • 1
  • 4

2 Answers2

0

All you have to do is execute following query using Java on your database.

SELECT 
  TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_SCHEMA = '<database>' 

Reference: How do I see all foreign keys to a table or column?

Vicky Thakor
  • 3,847
  • 7
  • 42
  • 67
0

Vendor independently one can use the DatabaseMetaData with its getExportedKeys and getImportedKeys on all tables.

DatabaseMetaData meta = conn.getMetaData();
try (ResultSet rs = meta.getExportedKeys(conn.getCatalog(), null, null)) {
    while (rs.next()) {
        String pkTable = rs.getString("PKTABLE_NAME");
        String fkTable = rs.getString("FKTABLE_NAME");
        String fkColumn = rs.getString("FKCOLUMN_NAME");
        int keySeq = rs.getInt("KEY_SEQ");
        ...
    }
}
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138