Home >Java >javaTutorial >How do I retrieve column names from a java.sql.ResultSet?
Accessing a column's name by its index using java.sql.ResultSet can be achieved through the ResultSet metadata. Here's how you can do it:
Execute your database query and store the result set in the rs variable:
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
Obtain the ResultSet metadata using the getMetaData() method:
ResultSetMetaData rsmd = rs.getMetaData();
Use the getColumnName() method of ResultSet metadata to retrieve the column name at a specific index (starting from 1):
String name = rsmd.getColumnName(1);
This will give you the column name as a String.
If you have an expression like SELECT x AS y in your query, you can also retrieve the retrieved label name using getColumnLabel():
String label = rsmd.getColumnLabel(1);
Consider the following query:
SELECT a, b, c FROM TABLE2;
Using the code provided above, you can access the column names for the ResultSet as follows:
name = rsmd.getColumnName(1); // will return "a" label = rsmd.getColumnName(1); // will also return "a"
The name and label variables will now hold the respective column names.
The above is the detailed content of How do I retrieve column names from a java.sql.ResultSet?. For more information, please follow other related articles on the PHP Chinese website!