Way2Java

ResultSetMetaData Get Table Metadata JDBC

What is metadata of a table?

The number of columns, data type of each column, name of each column, primary keys etc. constitutes the metadata of a table.

Actual data refers the records in the table.

Using JDBC, metadata of a table can be retrieved. The ResultSetMetaData interface can hold the metadata of the table returned by the database.

In the following program, records are printed along with column names (using metadata).

import java.sql.*;
public class MetaData
{
  public static void main(String args[]) throws Exception
  {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:snrao", "scott", "tiger");
    Statement stmt = con.createStatement();
                     
    ResultSet res = stmt.executeQuery("select *from Employee");
                                           // extract meta data from the ResultSet object
    ResultSetMetaData rsmd = res.getMetaData();
                                           // to print column names
    for( int i = 0; i < rsmd.getColumnCount(); i++)
    {
      System.out.print( rsmd.getColumnLabel(i+1) + "\t");
    }
                                           // column numbers start from 1
    System.out.println();                  // to give a new line
                                           // to print the records
    while(res.next())
    {
      System.out.println(res.getInt(1) + "\t" + res.getString(2) + "\t" + res.getDouble(3));	
    }

    res.close();
    stmt.close();
    con.close();
  }
} 

  1. getMetaData() is a method of ResultSet interface that returns an object of ResultSetMetaData interface.
  2. ResultSetMetaData object contians the metadata of the table.
  3. getColumnCount() and getColumnLabel() methods of ResultSetMetaData interface returns the number of columns(fields) of a table and label(name) of each column respectively.
  4. Column numbers start from 1 where as loop starts from 0. For this reason, i+1 is given as method parameter.