Retrieve column names from java.sql.ResultSet

In this example, we will discuss how to get column names from a database table using java.sql.ResultSet.
We can get table columns from the ResultSet getMetaData() method returns ResultSetMetaData interface object. ResultSetMetaData interface object that can be used to get information about the types and properties of the columns in a ResultSet object.
Consider we have a users table in the database. The following DDL script shows there are five columns in a users table.
create table Users1(
     id  int(3) primary key,
     name varchar(20),
     email varchar(20),
     country varchar(20),
     password varchar(20)
  );
Now, we will write a JDBC code to get all these columns from users table. The following fragment of code shows the same.

Retrieve column names from java.sql.ResultSet

Here is the complete program to retrieve column names from java.sql.ResultSet:
package com.javaguides.jdbc.databasemetadata;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Get column names from database table
 * @author Ramesh Fadatare
 *
 */
public class ResuleSetMetaDataExample {
    private static final String QUERY = "select id,name,email,country,password from Users";

    public static void main(String[] args) {

        // using try-with-resources to avoid closing resources (boiler plate code)

        // Step 1: Establishing a Connection
        try (Connection connection = DriverManager
            .getConnection("jdbc:mysql://localhost:3306/mysql_database?useSSL=false", "root", "root");
            // Step 2:Create a statement using connection object
            Statement stmt = connection.createStatement();
            // Step 3: Execute the query or update query
            ResultSet rs = stmt.executeQuery(QUERY)) {
            ResultSetMetaData resultSetMetaData = rs.getMetaData();
            System.out.println(resultSetMetaData.getColumnName(1));
            System.out.println(resultSetMetaData.getColumnName(2));
            System.out.println(resultSetMetaData.getColumnName(3));
            System.out.println(resultSetMetaData.getColumnName(4));
            System.out.println(resultSetMetaData.getColumnName(5));

        } catch (SQLException e) {
            printSQLException(e);
        }
        // Step 4: try-with-resource statement will auto close the connection.
    }

    public static void printSQLException(SQLException ex) {
        for (Throwable e: ex) {
            if (e instanceof SQLException) {
                e.printStackTrace(System.err);
                System.err.println("SQLState: " + ((SQLException) e).getSQLState());
                System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
                System.err.println("Message: " + e.getMessage());
                Throwable t = ex.getCause();
                while (t != null) {
                    System.out.println("Cause: " + t);
                    t = t.getCause();
                }
            }
        }
    }
}
Output:
id
name
email
country
password

Reference

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments