How to get foreign key reference with Derby JDBC?

1.5k views Asked by At

I have tables created with

CREATE TABLE COUNTRY (NAME CHAR(16) PRIMARY KEY)
CREATE TABLE PERSON (NAME CAHR(32) PRIMARY KEY,
       CITIZENSHIP CHAR(16) CONSTRAINT CY_FK REFERENCES COUNTRY (NAME))

So how can I get Table.Column (COUNTRY.NAME) reference of the foreign key after I've performed SELECT query on PERSON table? Is it possible to do via JDBC ResultSet, ResultSetMetaData or something alike?
In fact, I need to know:

  • either column has a Foreign Key constraint;
  • list of constraint values.

Well, I did SELECT on SYS.SYSCONSTRAINTS but there are only types of constraints ('P', 'F', etc) but no Referenced Tables' names.

Update

I send queries to the Database via JDBC

PreparedStatement stmtDerbyDb = DriverManager.getConnection(dbConnectString).prepareStatement("SELECT * FROM \"" + dbTableOrView + "\"");
ResultSet rsltDerbyDb = stmtDerbyDb.executeQuery();
ResultSetMetaData rsmdDerbyDb = rsltDerbyDb.getMetaData();
...

All the variables stmtDerbyDb, rsltDerbyDb, rsmdDerbyDb are used in further code. I need to know: is it possible to fetch Foreign Key constraints from dbTableOrView via JDBC or shall I query SYS.* system tables somehow?

1

There are 1 answers

2
Umbra Aeternitatis On

Possible decision:

...
Connection connTableView = DriverManager.getConnection("jdbc:Derby:database_name:create=false");
DatabaseMetaData dbmdTableView = connTableView.getMetaData();
ResultSet rsltTableConstraints = dbmdTableView.getImportedKeys(null, null, "PERSON");
PreparedStatement prstTableContents = connTableView.prepareStatement("SELECT * FROM PERSON");
ResultSet rsltTableContents = prstTableContents.executeQuery();
...
buildTableView(rsltTableContents);
rsltTableContents.close();
...
while (rsltTableConstraints.next()) {
    PreparedStatement prstConstraints = connTableView.prepareStatement("SELECT " + rsltTableConstraints.getString("PKCOLUMN_NAME") + " FROM " + rsltTableConstraints.getString("PKTABLE_NAME"));
    ResultSet rsltConstraintsForCol = prstConstraints.execute();
    ...
    setColumnConstraints(rsltConstraintsForCol, rsltTableConstraints.getString("FKCOLUMN_NAME"));
    ...
    rsltConstraintForCol.close();
    prstConstraints.close();
}
...

Which is supposed to be used as ComboBox dropdowns with constraints per column (with FK of course).