Sunday, September 15, 2019

Java ResultSetMetaData Interface

The metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name, column type etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet object.

Commonly used methods of ResultSetMetaData interface

MethodDescription
public int getColumnCount()throws SQLExceptionit returns the total number of columns in the ResultSet object.
public String getColumnName(int index)throws SQLExceptionit returns the column name of the specified column index.
public String getColumnTypeName(int index)throws SQLExceptionit returns the column type name for the specified index.
public String getTableName(int index)throws SQLExceptionit returns the table name for the specified column index.


How to get the object of ResultSetMetaData:

The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData. Syntax:
  1. public ResultSetMetaData getMetaData()throws SQLException  

Example of ResultSetMetaData interface :

  1. import java.sql.*;  
  2. class Rsmd{  
  3. public static void main(String args[]){  
  4. try{  
  5. Class.forName("oracle.jdbc.driver.OracleDriver");  
  6. Connection con=DriverManager.getConnection(  
  7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  8.   
  9. PreparedStatement ps=con.prepareStatement("select * from emp");  
  10. ResultSet rs=ps.executeQuery();  
  11. ResultSetMetaData rsmd=rs.getMetaData();  
  12.   
  13. System.out.println("Total columns: "+rsmd.getColumnCount());  
  14. System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));  
  15. System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));  
  16.   
  17. con.close();  
  18. }catch(Exception e){ System.out.println(e);}  
  19. }  
  20. }  
Output:Total columns: 2
       Column Name of 1st column: ID
       Column Type Name of 1st column: NUMBER

No comments:

Post a Comment

How to DROP SEQUENCE in Oracle?

  Oracle  DROP SEQUENCE   overview The  DROP SEQUENCE  the statement allows you to remove a sequence from the database. Here is the basic sy...