03
Oct

Working with ResultSet metada

Working with ResultSet metada

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”.

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 SR

*/

public class ResultSetMetaDataExample {

public static void main(String[] args) {

String jdbcUrl = “jdbc:mysql://10.9.121.6:3306/DBName”;

String username = “username”;

String password = “pwd”;

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=joe@example.com

UID=2

NAME=Andrew

DOB=1975-05-20

EMAIL=andrew@example.com