How to get Column name on ResultSet in Java with MySQL?


To get the column name on the result set, you need to use getMetaData() method. The prototype of getMetadata() is as follows −

ResultSetMetaData getMetaData throws SQLException;

Create a MySQL table with 5 column names. The query to create a table is as follows −

mysql> create table javagetallcolumnnames
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(20),
   -> Age int,
   -> Salary float,
   -> Address varchar(100),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (1.34 sec)

The following is the Java code that gets the column name on ResultSet. The code is as follows −

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.ResultSetMetaData;
public class GetAllColumnNames {
   public static void main(String[] args) {
      String JdbcURL="jdbc:mysql://localhost:3306/test?useSSL=false";
      String Username="root";
      String password="123456";
      Connection con=null;
      Statement stmt=null;
      ResultSet rs;
      try {
         con = DriverManager.getConnection(JdbcURL, Username, password);
         stmt=con.createStatement();
         rs = stmt.executeQuery("SELECT *FROM javagetallcolumnnames");
         ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData();
         int counter = md.getColumnCount();
         String colName[] = new String[counter];
         System.out.println("The column names are as follows:");
         for (int loop = 1; loop <= counter; loop++) {
            colName[loop-1] = md.getColumnLabel(loop);
            System.out.println(colName[loop-1]);
         }
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

Here is the snapshot of the code −

The following is the output −

The column names are as follows:
Id
Name
Age
Salary
Address

Here is the snapshot of the sample output −

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

473 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements