Tuesday, June 7, 2011

How to Get Column Names for a Table

For Fetching column names of a table ResultSetMetaData is used in JDBC .

package org.best.examples;

import java.sql.*;

public class GetColNames
    {
   
    public static void main(String args[])
        {
         try
             {
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
             Connection connection = DriverManager.getConnection("jdbc:odbc:dd","","");
             // Create a result set
             Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM test");
           
             // Get result set meta data
             ResultSetMetaData rsmd = rs.getMetaData();
             int numColumns = rsmd.getColumnCount();
           
             // Get the column names; column indices start from 1
             for (int i=1; i                 {
                 String columnName = rsmd.getColumnName(i);
               
                 // Get the name of the column's table name
                 String tableName = rsmd.getTableName(i);
                 System.out.println("columnName "+columnName);
             }
         }
         catch (Exception e)
             {
             System.out.println(e);
         }
    }
}

No comments: