Java ResultSet - 根据索引获取列名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6409371/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:42:02  来源:igfitidea点击:

Java ResultSet - get Column name based on Index

javajdbc

提问by Rudy

I want to know if there is a way to get a column name based on the index from a resultSet.

我想知道是否有办法根据结果集的索引获取列名。

I know that if you want to get index based on the columnName, you can do that by using

我知道如果你想根据 columnName 获取索引,你可以使用

int index = resultSet.findColumn(columnName);

But I need the other way around, something like :

但我需要相反的方式,例如:

String column = resultSet.findColumnName(index);

Is it possible?

是否可以?

采纳答案by Jon Skeet

I think you need to look at ResultSet.getMetaData()which returns the meta-data associated with a ResultSet.

我认为您需要查看ResultSet.getMetaData()哪个返回与ResultSet.

You can then iterate over the columns (use getColumnCount()to find out how many there are) to find the column with the given name, checking with getColumnName(). Don't forget that column indexes are 1-based, rather than 0-based. Something like:

然后,您可以遍历列(用于getColumnCount()找出有多少列)以查找具有给定名称的列,并使用getColumnName(). 不要忘记列索引是从 1 开始的,而不是从 0 开始的。就像是:

ResultSetMetaData metaData = resultSet.getMetaData();

int count = metaData.getColumnCount();
for (int i = 1; i <= count; i++)
{
    if (metaData.getColumnName(i).equals(desiredColumnName))
    {
        // Whatever you want to do here.
    }
}

If you need to do this for a lot of names, you may want to build a HashMap<String, Integer>to map them easily.

如果您需要为大量名称执行此操作,您可能需要构建一个HashMap<String, Integer>来轻松映射它们。

回答by duffymo

Of course - use java.sql.ResultSetMetaData.

当然 - 使用java.sql.ResultSetMetaData

ResultSetMetaData meta = resultSet.getMetaData();
String column = meta.getColumnName(index);

回答by Bj?rn Pollex

resultSet.getMetaData().getColumnName(index);

回答by Andrzej Doyle

With standard JDBC, you can get the result set's metadata:

使用标准 JDBC,您可以获得结果集的元数据

ResultSetMetaData metadata = resultSet.getMetaData() 

This object can then be queried for the column name (by index):

然后可以查询此对象的列名(按索引):

String columnFiveName = metadata.getColumnName(5)

回答by Jigar Joshi

How about ResultSetMetaData'sgetColumnName()?

怎么样ResultSetMetaDatagetColumnName()



For Example:

例如:

ResultSetMetaData metaData = resultSet.getMetaData()
metaData.getColumnName(1) ;


See Also

也可以看看

回答by Bruno

You should be able to do this using ResultSetMetaData:

您应该能够使用ResultSetMetaData做到这一点:

ResultSetMetaData rsmd = resultSet.getMetaData();
String column = rsmd.getColumnName(index);