Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

With java.sql.ResultSet is there a way to get a column's name as a String by using the column's index? I had a look through the API doc but I can't find anything.

2 Answers

0 votes
by (46k points)

You can get the aforementioned info from the ResultSet metadata. Descry ResultSetMetaData

e.g.

 ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");

 ResultSetMetaData rsmd = rs.getMetaData();

 String name = rsmd.getColumnName(1);

and you can notice the column name from there. If you do

choose x as y from table

then rsmd.getColumnLabel() will get you the retrieved label name also.

0 votes
ago by (1.8k points)

We can retrieve column names from java.sql.ResultSet to retrieve this we have to use ResultSetMetaData interface because this interface provides some methods with the help of which we can retrieve metadata about the columns in a resultset which includes their names,type and some other properties as well. 

import java.sql.*;

public class Example {

    public static void main(String[] args) throws SQLException {

        // Assuming you have a valid ResultSet object called resultSet

        ResultSet resultSet = ...;

        ResultSetMetaData metaData = resultSet.getMetaData();

        int columnIndex = 1;  // Replace with your column index

        String columnName = metaData.getColumnName(columnIndex);

        System.out.println("Column name: " + columnName);

    }

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Dec 6, 2020 in SQL by Appu (6.1k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...