Turn Desktop View Off
by Dinesh Thakur

The ResultSetMetaDa ta interface provides methods that allow you to get metadata for the resultset, that is, the number, types and properties of the columns in a ResultSet object. This information is used to collect the data with same semantics but stored in different databases in different formats.

To get this information of columns in the ResultSet object using methods of the ResultSetMetaData interface, it is required to invoke the getMetaData () method of the ResultSet object that returns a reference to an object of type ResultSetMetaData.

Some of the methods of ResultSetMetaData interface are as follows.

• Int getColumnCount() :This method returns the number of columns in the resultset.

• String getColumnName(int index) :This method returns the name of column specified by index value index in the resultset.

• int getColumnType(int index) :This method returns the type of column specified by index value index in the resultset.

program to demonstrate implementation of ResultSetMetaData and ResultSet interface.

import java.sql.*;

class ExampleResultSetMetaData

{

   public static void main(String args[])

   {

       Connection con;

       Statement stmt;

       ResultSet rs;

       try

         {

              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

              con= DriverManager.getConnection("jdbc:odbc:Emp");

              stmt = con.createStatement();

              rs = stmt.executeQuery("Select * from Employee WHERE Department='Math'");

              ResultSetMetaData rsmd = rs.getMetaData();

              int col= rsmd.getColumnCount();

              //returns number of columns

              int row = 1;

              while (rs.next())

                    {

                         System.out.println("Row" +row+": ");

                         for (int i = 1; i <= col; i++)

                             {

                                 System.out.print(" Column"+ i + ": ");

                                 System.out.println(rs.getString(i));

                             }

                                 System.out.println(" ");

                                 row++;

                   }

                         stmt.close();

                         con.close();

       }

                  catch(Exception e)

                     {

                         System.err.print("ClassNotFoundException: ");

                         System.err.println(e.getMessage());

                     }

    }

}