What is ResultSetMetaData in JDBC? What is its significance?

The ResultSetMetaData provides information about the obtained ResultSet object like, the number of columns, names of the columns, datatypes of the columns, name of the table etc…

Following are some methods of ResultSetMetaData class.

getColumnCount()Retrieves the number of columns in the current ResultSet object.
getColumnLabel()Retrieves the suggested name of the column for use.
getColumnName()Retrieves the name of the column.
getTableName()Retrieves the name of the table.


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class ResultSetMetadataExample {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/TestDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating a Statement object
      Statement stmt = con.createStatement();
      //Retrieving the data
      ResultSet rs = stmt.executeQuery("select * from Dataset");
      ResultSetMetaData rsMetaData = rs.getMetaData();
      //Number of columns
      System.out.println("Number of columns: "+rsMetaData.getColumnCount());
      //Column label
      System.out.println("Column Label: "+rsMetaData.getColumnLabel(1));
      //Column name
      System.out.println("Column Name: "+rsMetaData.getColumnName(1));
      //Number of columns
      System.out.println("Table Name: "+rsMetaData.getTableName(1));


Connection established......
Number of columns: 2
Column Label: mobile_brand
Column Name: mobile_brand
Table Name: dataset