JDBC - ResultSetMetaData example

Posted on February 12, 2017


Technologies used:   JDK 1.8.0_121 | MySQL 5.7.12 | Eclipse Mars.2 (4.5.2)

A ResultSetMetaData object is used to get metadata (i.e. data about data) of the columns from query’s result.

The ResultSetMetaData object provides the following information -

  • Number of columns in a table.
  • Type of columns.
  • Name of columns.
  • Size of columns.

The following example demonstrates how to get metadata from query’s result using the ResultSetMetaData.

ResultSetMetaDataExample.java

package com.boraji.tutorial.jdbc;

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

/**
 * @author imssbora
 */
public class ResultSetMetaDataExample {

  public static void main(String[] args) {
    String jdbcUrl = "jdbc:mysql://localhost:3306/BORAJI";
    String username = "root";
    String password = "admin";
    String sql = "select * from users";

    try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password); 
        PreparedStatement stmt = conn.prepareStatement(sql);) {

      try (ResultSet rs = stmt.executeQuery();) {
        ResultSetMetaData metaData = rs.getMetaData();

       
        System.out.println("---------------META DATA-------------");
        int numOfCols = metaData.getColumnCount();
        for (int i = 1; i <= numOfCols; i++) {
          String colType = metaData.getColumnTypeName(i);
          String colName = metaData.getColumnName(i);
          int size = metaData.getColumnDisplaySize(i);
          System.out.println("Column Name=" + colName + "\t Type=" + colType+"\t Size="+size);
        }
        
        System.out.println("\n---------------RESULT-------------");
        
        while(rs.next()){
          System.out.println("UID="+rs.getString(1));
          System.out.println("NAME="+rs.getString(2));
          System.out.println("DOB="+rs.getString(3));
          System.out.println("EMAIL="+rs.getString(4));
          System.out.println();
        }
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}

Output

---------------META DATA-------------
Column Name=UID	 Type=INT	 Size=11
Column Name=NAME	 Type=VARCHAR	 Size=45
Column Name=DOB	 Type=DATE	 Size=10
Column Name=EMAIL	 Type=VARCHAR	 Size=45

---------------RESULT-------------
UID=1
NAME=Joseph
DOB=1988-12-25
[email protected]

UID=2
NAME=Andrew
DOB=1975-05-20
[email protected]