«Back to Home

Core Java

Topics

ResultSetMetaData Interface In Java

ResultSetMetaData Interface
 
In JDBC, metadata means data about the data, that is to say, we can get further information from the data and if we have to get metadata of a table like total number of columns, columns name, columns type etc. ResultSetMetaData interface is very useful because it provides methods to get metadata from the ResultSet object.
 
Methods of ResultSetMetaData interface

public int getColumnCount()throws SQLException

This method is used to return the total number of columns in the ResultSet object.
 
public String getColumnName(int index)throws SQLException

This method is used to return the column name of the specified column index.
 
public String getColumnTypeName(int index)throws SQLException

This method is used to return the column type name for the specified index.
 
public String getTableName(int index)throws SQLException

This method is used to return the table name for the specified column index.
 
Get the ResultSetMetaData object

The getMetaData() method of ResultSet interface is used to return the object of ResultSetMetaData.
 
Syntax

public ResultSetMetaData getMetaData()throws SQLException
 
Let’s see an example, given below.
 
Code
  1. import java.sql.*;  
  2. public class StudentDatabase2 {  
  3.     public static void main(String args[]) throws Exception {  
  4.   
  5.         Class.forName("org.apache.derby.jdbc.ClientDriver");  
  6.         String url = "jdbc:derby://localhost:1527/Student";  
  7.         String username = "Student";  
  8.         String password = "student";  
  9.         Connection conn = DriverManager.getConnection(url, username, password);  
  10.         PreparedStatement ps = conn.prepareStatement("select * from STUDENT.STUDENTDB");  
  11.         ResultSet rs = ps.executeQuery();  
  12.         ResultSetMetaData re = rs.getMetaData();  
  13.         System.out.println("Total Columns: " + re.getColumnCount());  
  14.         System.out.println("Column Name of 1st column: " + re.getColumnName(1));  
  15.         System.out.println("Column Type Name of 1st column: " + re.getColumnTypeName(1));  
  16.         conn.close();  
  17.     }  
  18. }  
22
 
Output

23

Summary

Thus, we learnt, JDBC Metadata means data about data, which states we can get the further information from the data and if we have to get the metadata of a table like total number of columns, columns name, columns type etc. and also learnt its important methods in Java.