如何从 JAVA 中的 ResultSet 或 ResultSetMetaData 对象中获取数据库表的主键的列名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2212997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the column name of the primary key of a Database Table from the ResultSet or ResultSetMetaData object in JAVA?
提问by Yatendra Goel
I am writing a Java Application. I have got a ResultSet. Now I want to find out the coloumn name of the primary key of the table.
我正在编写一个 Java 应用程序。我有一个结果集。现在我想找出表的主键的列名。
Is it possible to get that coloumn name through ResultSet object or ResultSetMetaData Object or any other way.
是否可以通过 ResultSet 对象或 ResultSetMetaData 对象或任何其他方式获得该列名称。
I didn't find any way to find this.
我没有找到任何方法来找到这个。
回答by Pablo Santa Cruz
No. You will not get that information from ResultSetor ResultSetMetadata.
不。您不会从ResultSet或ResultSetMetadata获得该信息。
What you want to use for that is DatabaseMetadataclass. From that class check getPrimaryKeysmethod to get the information you want.
您想要使用的是DatabaseMetadata类。从该类检查getPrimaryKeys方法以获取您想要的信息。
Of course, to use this, you will need to know the name of the table.
当然,要使用它,您需要知道表的名称。
回答by swdev
I want to add, if in a table you have autoincrement field, it must be the primary key. So, your code could look like this:
我想补充一点,如果在表中有自动增量字段,它必须是主键。因此,您的代码可能如下所示:
if(metaColumn.isAutoIncrement(i)) {
primaryKey = metaColumn.getColumnName(i);
i=nColoumn+1;
}
It uses ResultSetMetaData.
它使用ResultSetMetaData.
回答by mjn
A nice tool which you can use to verify the metadata information is dbVisualizer.
可用于验证元数据信息的一个不错的工具是dbVisualizer。
It uses the JDBC metadata to retrieve table definitions and other parts of the database. Schema and Catalog are columns in the table definition view - so you can check which values are in these columns for your favorite database.
它使用 JDBC 元数据来检索表定义和数据库的其他部分。Schema 和 Catalog 是表定义视图中的列 - 因此您可以检查您最喜欢的数据库的这些列中有哪些值。
dbVisualizer is available in a free basic version.
dbVisualizer 提供免费的基本版本。

