How to get the name of column in a table with JDBC?

Column name JDBC

ResultSetMetaData interface comes with methods to know the metadata of a table. Metadata is knowing the number of columns, name of each column etc. Example (of column name JDBC) prints the first column name and all the column names of table Employee.

Example on column name JDBC
import java.sql.*;
public class MetaData
{
  public static void main(String args[]) throws Exception
  {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:snrao", "scott", "tiger");
    Statement stmt = con.createStatement();
                     
    ResultSet res = stmt.executeQuery("select *from Employee");
                                                     // extract meta data from the ResultSet object
    ResultSetMetaData rsmd = res.getMetaData();

    String firstColumnName = rsmd.getColumnName(1);  // prints first column name
    System.out.println("First column name is " + firstColumnName);
                                                     // to print all column names in a loop
    int numOfColumns = rsmd.getColumnCount();
    for(int i = 0; i < numofColumns; i++)
    {
      System.out.println(rsmd.getColumnName(i+1));
    }
                        
    res.close();
    stmt.close();
    con.close();
  }
} 
  1. getMetaData() is a method of ResultSet interface. The method returns an object of ResultSetMetaData interface.
  2. ResultSetMetaData object contains the metadata of the table.
  3. getColumnCount() method of ResultSetMetaData interface returns the number of columns(fields) of a table.
  4. getColumnName(int columnNumber) method of ResultSetMetaData interface returns the name of the column, passed as parameter.

System.out.println(rsmd.getColumnName(i+1));

Columns numbers start from 1 (and not 0) but loop starts from 0.

Pass your comments and suggestions on this tutorial "column name JDBC" to improve the quality.

Leave a Comment

Your email address will not be published.