How to get Table Column Names in Java using DatabaseMetadata?

Below Java code shows how to get Table Column name using DatabaseMetadata-

/****************************************************************************************
 * Created on 05-2011 Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.javasql;

import java.sql.*;

/**
 * Created by http://kodehelp.com
 * Date: 5/9/11
 */
public class GetTableColumnNames {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        final String driver = "oracle.jdbc.driver.OracleDriver";
        final String url = "jdbc:oracle:thin:@HOST:PORT:SID";
        final String USERNAME = "USERNAME";
        final String PASSWORD = "PASSWORD";
        Connection conn = null;
        try{
          Class.forName(driver); // load Oracle driver
          conn = DriverManager.getConnection(url, USERNAME, PASSWORD);
          DatabaseMetaData databaseMetaData = conn.getMetaData();

          ResultSet resultSet = databaseMetaData.getColumns(null, null, "users", null);
          while (resultSet.next()) {
            String name = resultSet.getString("COLUMN_NAME");
            String type = resultSet.getString("TYPE_NAME");
            int size = resultSet.getInt("COLUMN_SIZE");
            System.out.println("Column name: [" + name + "]; type: [" + type
            + "]; size: [" + size + "]");
          }
        }catch (ClassNotFoundException cnfEx){
            throw cnfEx;
        }catch (SQLException sqlEx){
            throw sqlEx;
        }finally{
            if(conn!=null){
                conn.close();
            }
        }
    }
}

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.