Get

Get "Schema" of a table using "ResultSetMetaData"


Posted in : Core Java Posted on : October 18, 2010 at 3:58 PM Comments : [ 0 ]

This section contains the detail about the Getting "Schema" of a table using "ResultSetMetaData" in java.

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

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics