DatabaseMetaData 인터페이스에서 제공되는 getImportedKeys, getExportedKeys, getCrossReference 메소드를 사용하여 외래 키 정보를 확인할 수 있다. 각 메소드의 사용법 및 예제는 다음과 같다.
getImportedKeys(String catalog, String schema, String table)
getExportedKeys(String catalog, String schema, String table)
getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable)
위 메소드를 호출하면 아래와 같이 14개의 컬럼으로 구성된 ResultSet을 반환한다.
name |
type |
비고 |
---|---|---|
PKTABLE_CAT |
String |
항상 null |
PKTABLE_SCHEM |
String |
항상 null |
PKTABLE_NAME |
String |
기본 키 테이블 이름 |
PKCOLUMN_NAME |
String |
기본 키 컬럼 이름 |
FKTABLE_CAT |
String |
항상 null |
FKTABLE_SCHEM |
String |
항상 null |
FKTABLE_NAME |
String |
외래 키 테이블 이름 |
FKCOLUMN_NAME |
String |
외래 키 컬럼 이름 |
KEY_SEQ |
short |
외래 키 또는 기본 키 컬럼들의 순서(1부터 시작) |
UPDATE_RULE |
short |
기본 키가 업데이트될 때 외래 키에 대해 정의된 참조 동작에 대응되는 값 |
DELETE_RULE |
short |
기본 키가 삭제될 때 외래 키에 대해 정의된 참조 동작에 대응되는 값 |
FK_NAME |
String |
외래 키 이름 |
PK_NAME |
String |
기본 키 이름 |
DEFERRABILITY |
short |
항상 6 (DatabaseMetaData.importedKeyInitiallyImmediate) |
ResultSet rs = null;
DatabaseMetaData dbmd = conn.getMetaData();
System.out.println("\n===== Test getImportedKeys");
System.out.println("=====");
rs = dbmd.getImportedKeys(null, null, "pk_table");
Test.printFkInfo(rs);
rs.close();
System.out.println("\n===== Test getExportedKeys");
System.out.println("=====");
rs = dbmd.getExportedKeys(null, null, "fk_table");
Test.printFkInfo(rs);
rs.close();
System.out.println("\n===== Test getCrossReference");
System.out.println("=====");
rs = dbmd.getCrossReference(null, null, "pk_table", null, null, "fk_table");
Test.printFkInfo(rs);
rs.close();