从ResultSet Java获取主键列 [英] Get Primary Key Column from ResultSet Java

查看:261
本文介绍了从ResultSet Java获取主键列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从ResultSet获取表的主键列.以下是步骤

I am trying to get Primary Key Column(s) of table from ResultSet. Following are the Steps

我关注了:

1. SQL QUERY: Select id,subid,email,empname from Employee
2. Executed this from java.sql.Statement and got the Results in ResultSet.

这是有趣的部分.

3. ResultSetMetadata rsmd = rs.getMetadata();

现在,如果我看到此变量" rsmd ",它将显示相关列名的主键标志,但我无法访问它或将其放入任何变量中.

Now, if i watch this variable "rsmd" , it is showing primary key flags for relevant column names but I am not able to access it or get it into any variable.

我需要与此有关的帮助.

I need help regarding the same.

注意:我不想使用DatabaseMetadata及其getPrimaryKeys()函数,因为它将对外部数据库产生额外的影响.另外,ResultSetMetadata对象已经具有我只需要获取的主键信息.

NOTE: I do not want to use DatabaseMetadata and its getPrimaryKeys() function as it will take an additonal hit into External Database. Also, the ResultSetMetadata object is already having the primary key Information which i just need to fetch.

推荐答案

我有一个想法,可以使用ResultSet检查表中的列是否为主键.

I have an idea to check whether a Column in table is Primary key or not using ResultSet.

在MySql JDBC驱动程序中,如果仔细看一下,java.sql.ResultSetMetaData的实际实现类将是com.mysql.jdbc.ResultSetMetaData类.此类提供了protected方法来获取有关每个字段的信息

In MySql JDBC driver, if you take a closer look, the real implementation class of java.sql.ResultSetMetaData would be com.mysql.jdbc.ResultSetMetaData class. This class provides a protected method to get information about each field

protected Field getField(int columnIndex) throws SQLException {

此方法可以为每个column索引提供Field实例. 使用Field实例,您可以访问Field的属性.要检查它是否为主键,可以调用

This method can give you the Field instance for every column index. Using the Field instance, you can get to the properties of the Field. To check whether it is a primary key, you can invoke

Field.isPrimaryKey() 

使用类型为((com.mysql.jdbc.ResultSetMetaData) rsmd).getField(i).isPrimaryKey()的类型的com.mysql.jdbc.ResultSetMetaData的FQN.这是因为您不能导入两个具有相同名称的类文件并在文件中使用它们

Use FQN of com.mysql.jdbc.ResultSetMetaData in your type cast like ((com.mysql.jdbc.ResultSetMetaData) rsmd).getField(i).isPrimaryKey(). This is because you cannot import two class files with the same name and use them across the file

请阅读MySql中 Field 的文档JDBC API可以了解更多有关它的信息.希望这会有所帮助!

Please read the documentation of Field from MySql JDBC API to learn more about it. Hope this helps!

这篇关于从ResultSet Java获取主键列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆