[英]Get all foreign keys using JDBC
I am using postgreSQL. 我正在使用postgreSQL。 I am trying to get all of the foreign keys from a table.
我试图从表中获取所有外键。 This is the method that I am currently using.
这是我目前使用的方法。
public String getFKeyData(String tableName, int i) throws SQLException {
DatabaseMetaData dm = connection.getMetaData();
ResultSet rs = dm.getImportedKeys(null, null, tableName);
while (rs.next()) {
fkTableData = rs.getString(i);
}
return fkTableData;
}
This code works but it only gets me the last foreign key which is fine if there is only one in the table but this does not fit my needs. 这段代码有效,但它只能得到我最后一个外键,如果表中只有一个,但这不符合我的需要。 All of the examples I have looked at online are very similar to this and only give one foreign key as an output.
我在网上看到的所有例子与此非常相似,只提供一个外键作为输出。 Currently I am just printing the data when a button is pressed.
目前我只是在按下按钮时打印数据。
System.out.println(databaseConnection.getFKeyData(tableName,3));
System.out.println(databaseConnection.getFKeyData(tableName,4));
System.out.println(databaseConnection.getFKeyData(tableName,8));
3 gets the table the foreign key was imported from. 3获取从中导入外键的表。 4 gets the name of the primary key column which is imported.
4获取导入的主键列的名称。 8 gets the name of foreign key column.
8获取外键列的名称。 If anyone can help I would greatly appreciate it.
如果有人可以提供帮助,我会非常感激。
Even though your while loop iterates over the whole ResultSet
, the function will only return the last column in a FK constraint because on each iteration you overwrite the value of the previous iteration ( fkTableData = rs.getString(i);
). 即使您的while循环遍历整个
ResultSet
,该函数也只会返回FK约束中的最后一列,因为在每次迭代时都会覆盖前一次迭代的值( fkTableData = rs.getString(i);
)。 Btw: `fkTableData should actually be a local variable to the method, not an instance variable. 顺便说一下:`fkTableData实际上应该是方法的局部变量,而不是实例变量。
Your function should return a List<String>
not a String
. 您的函数应该返回
List<String>
而不是String
。
Additionally: you are calling getImportedKeys()
once for each column in the ResultSet. 另外:您为ResultSet中的每个列调用一次
getImportedKeys()
。 That is extremely inefficient. 这是非常低效的。 If you were using Oracle you'd notice that immediately because retrieving FK information is extremely slow there (Postgres is much faster when accessing the system catalogs).
如果您使用的是Oracle,您会立即注意到,因为检索FK信息的速度非常慢(Postgres在访问系统目录时要快得多)。
As getImportedKeys()
returns one row for each FK column you also need to collect all rows that belong to one single constraint definition (ie for one parent/child table combination). 由于
getImportedKeys()
为每个FK 列返回一行,您还需要收集属于一个约束定义的所有行(即,对于一个父/子表组合)。
Probably the best thing would be to define a class PkDefinition
that stores all involved columns and the table names involved and have your function return List<PkDefinition>
to avoid multiple calls for the same result set row. 可能最好的方法是定义一个类
PkDefinition
,它存储所有涉及的列和所涉及的表名,并使您的函数返回List<PkDefinition>
以避免对同一结果集行进行多次调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.