Home Tutorial Java Jdbc Get "Schema" of a table using "ResultSetMetaData"

 
 

Get "Schema" of a table using "ResultSetMetaData"
Posted on: June 5, 2010 at 12:00 AM
Advertisement
In this section, schema of a table will be fetched by using 'Resultset' object and 'ResultSetMetaData' object .

GET "SCHEMA" OF A TABLE USING "RESULTSETMETADATA"  

In this section, schema of a table will be fetched by using 'Resultset' object and 'ResultSetMetaData' object .

  • For getting column name, we will use "getColumnName()" function. This function take 'column index number' as argument , index will be fetched by using "getColumnCount()"  function.
  • For getting maximum size of the column, we will use "getColumnDisplaySize()" function. This function take 'column index number' as argument .
  • For getting column's data type, we will use "getColumnTypeName()" function. This function take 'column index number' as argument.

getschema.java

import java.sql.*;
class getschema 
{
  public static void main(String[] args
  {
  Connection con=null;
  Statement st=null;
  ResultSet rs=null;

  try
  {
    Class.forName("com.mysql.jdbc.Driver");
    con=DriverManager.getConnection("jdbc:mysql://192.168.10.13:3306
    /ankdb"
,"root","root");
    st = con.createStatement();
    rs = st.executeQuery("select* from Emp_sal");
  
        ResultSetMetaData metaData = rs.getMetaData();
        int rowCount = metaData.getColumnCount();

        System.out.println("Table Name : " + metaData.getTableName(2));
        System.out.println("Field  \t\t\t\tsize\t\tDataType");

     for (int i = 0; i < rowCount; i++) {
     System.out.print(metaData.getColumnName(i + 1" \t\t\t"); 
     System.out.print(metaData.getColumnDisplaySize(i + 1"\t\t");
     System.out.println(metaData.getColumnTypeName(i + 1));
                                           }
     catch (Exception e) {
        System.out.println(e);
    }
  }
}

OUTPUT

C:\Program Files\Java\jdk1.6.0_18\bin>java getschema
Table Name : Emp_sal
Field                            size            DataType
Emp_code                   11             INTEGER
Emp_salary                  30            VARCHAR
Emp_designation          30            VARCHAR

Download Source Code

Advertisement

Related Tags for Get "Schema" of a table using "ResultSetMetaData":


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 5, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com