JDBC allows us to get metadata information of the DB and DB tables. Our aim here is to describe a table, we need to get the metadata of the DB table. We can achieve this with ResultSetMetaData interface.
All you need to do is -
1. just create a statement with plain select query i.e.;
SELECT * FROM EMPLOYEE
2. Get the ResultSetMetaData object reference using resultSet.getMetaData();
3. Access column name and data type
DescDemo.java
import java.sql.*;
/**
* A demo class to explain DESC DB table
* @author Santhosh Reddy Mandadi
* @since 17-Aug-2012
* @version 1.0
*/
public class DescDemo
{
public static void main(String args[]) throws Exception
{
String driverClass;
String jdbcURL;
String userName;
String password;
String tableName;
driverClass = "oracle.jdbc.driver.OracleDriver";
jdbcURL = "jdbc:oracle:@localhost:1521:xe";
userName = "scott";
password = "tiger";
tableName = "EMPLOYEE";
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(jdbcURL, userName, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM "+tableName);
ResultSetMetaData metaData = resultSet.getMetaData();
System.out.println("Number of columns: "+metaData.getColumnCount());
System.out.println("Table description...!");
for(int i=1;i< metaData.getColumnCount();i++)
{
System.out.println(metaData.getColumnName(i)+"\t"+metaData.getColumnTypeName(i));
}
}
}