20

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

int index = resultSet.findColumn(columnName);

But I need the other way around, something like :

String column = resultSet.findColumnName(index);

Is it possible?

Rudy
  • 7,008
  • 12
  • 50
  • 85

6 Answers6

41

I think you need to look at ResultSet.getMetaData() which returns the meta-data associated with a 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:

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
7

Of course - use java.sql.ResultSetMetaData.

ResultSetMetaData meta = resultSet.getMetaData();
String column = meta.getColumnName(index);
duffymo
  • 305,152
  • 44
  • 369
  • 561
2
resultSet.getMetaData().getColumnName(index);
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
0

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

ResultSetMetaData metadata = resultSet.getMetaData() 

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

String columnFiveName = metadata.getColumnName(5)
Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
0

How about ResultSetMetaData 'sgetColumnName() ?


For Example:

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

See Also

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
0

You should be able to do this using ResultSetMetaData:

ResultSetMetaData rsmd = resultSet.getMetaData();
String column = rsmd.getColumnName(index);
Bruno
  • 119,590
  • 31
  • 270
  • 376