Home > Java > javaTutorial > How do I retrieve column names from a java.sql.ResultSet?

How do I retrieve column names from a java.sql.ResultSet?

Mary-Kate Olsen
Release: 2024-11-15 04:21:02
Original
527 people have browsed it

How do I retrieve column names from a java.sql.ResultSet?

Retrieving Column Names from 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:

Get ResultSet and Metadata

Execute your database query and store the result set in the rs variable:

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

Obtain the ResultSet metadata using the getMetaData() method:

ResultSetMetaData rsmd = rs.getMetaData();
Copy after login

Retrieve Column Name

Use the getColumnName() method of ResultSet metadata to retrieve the column name at a specific index (starting from 1):

String name = rsmd.getColumnName(1);
Copy after login

This will give you the column name as a String.

Getting Column Label

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);
Copy after login

Example

Consider the following query:

SELECT a, b, c FROM TABLE2;
Copy after login

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"
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template