甲骨文設置:
CREATE TABLE test.parent_table (
id INT PRIMARY KEY
);
CREATE TABLE test.child_table (
id INT PRIMARY KEY,
parent_id INT REFERENCES parent_table (id),
prev_id INT REFERENCES child_table (id)
);
的Java代碼:
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DescribeDB {
public static void main(String[] args)
{
try{
Class.forName("oracle.jdbc.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:XE",
"username",
"password"
);
DatabaseMetaData md = con.getMetaData();
ResultSet rs = md.getImportedKeys(
con.getCatalog(),
"TEST",
"CHILD_TABLE"
);
while (rs.next()) {
System.out.println(
String.format(
"%s.%s.%s references %s.%s.%s",
rs.getString("FKTABLE_SCHEM"),
rs.getString("FKTABLE_NAME"),
rs.getString("FKCOLUMN_NAME"),
rs.getString("PKTABLE_SCHEM"),
rs.getString("PKTABLE_NAME"),
rs.getString("PKCOLUMN_NAME")
)
);
}
} catch(ClassNotFoundException | SQLException e) {
System.out.println(e);
}
}
}
輸出:
TEST.CHILD_TABLE.PREV_ID references TEST.CHILD_TABLE.ID
TEST.CHILD_TABLE.PARENT_ID references TEST.PARENT_TABLE.ID
來源
2016-05-30 20:25:10
MT0
您正在尋找['getImportedKeys()']( HTTP:// docs.oracle.com/javase/8/docs/api/java/sql/DatabaseMetaData.html#getImportedKeys-java.lang.String-java.lang.String-java.lang.String-)和['getExportedKeys()' ](http://docs.oracle.com/javase/8/docs/api/java/sql/DatabaseMetaData.html#getExportedKeys-java.lang.String-java.lang.String-java.lang.String-) –
但我不想要表的外鍵或主鍵,我想要包含它的表的名稱,並且我沒有foreigns或主鍵,我只有一個表的名稱 – WhiteShadow
那些調用** do **返回表名,請仔細閱讀JavaDocs。這是唯一可以返回這些信息的Java API。如果你不想這樣做,你需要創建自己的查詢,從'all_constraints'中獲取這些信息。 –