How to get Table Column Names in Java using DatabaseMetadata?

DeeKay May 9, 2011 at 5:38 pm · java.sql

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();
            }
        }
    }
}