MetaData

Learn how to fetch information about connection & resultset


Metadata is data about data i.e. table structure, dbms version, driver version. In java java.sql.DatabaseMetaData interface provide information about DBMS and Driver and java.sql.ResultSetMetaData is used to provide information about resultset i.e. data typeso of columns.


DatabaseMetaData


import java.sql.*; 
public class MyDatabaseMetadata  
 {
 public static void main(String a[]) throws Exception
  {
   Class.forName("oracle.jdbc.driver.OracleDriver");
   Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","root","root");
   
   // Get MetaData object
   DatabaseMetaData dm = con.getMetaData();
   
   // Print Driver information
   System.out.println(dm.getDriverVersion());
   System.out.println(dm.getDriverName());
   
   // Print DBMS information
   System.out.println(dm.getDatabaseProductName());
   System.out.println(dm.getDatabaseProductVersion());
        
    }
}


ResultSetMetaData

ResultSetMetaData interface extends Wrapper interface which used in jdbc classes which provide facility to retrieve information about ResultSet object.
Common methods used are

  • int getColumnCount()

  • String getColumnName()

  • int getColumnType()

  • String getTableName()
import java.sql.*; 
public class MyDatabaseMetadata  
 {
 public static void main(String a[]) throws Exception
  {
   Class.forName("oracle.jdbc.driver.OracleDriver");
   Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","root","root");
   
 
   Statement stmt=con.createStatement();
   ResultSet rs=stmt.executeQuery("select * from emp");
   
     // Get ResultSetMetaData object
   ResultSetMetaData rsmd = rs.getMetaData();
   int cols = rsmd.getColumnCount();
   System.out.println("Number of Columns fetched:"+cols);

   System.out.println("These columns are: ");
	for (int i=1;i<=cols;i++) 
	{
	String colName = rsmd.getColumnName(i);
	String colType = rsmd.getColumnTypeName(i);
    System.out.println("Column Name:"+colName);
	System.out.println("Data Type:"+colType);
    }  
  }
}