How to get number of columns in a table with JDBC?

Number of columns in table JDBC

ResultSetMetaData interface includes many methods to find the metadata of a table like number of columns, name of each column etc. Following example prints the number of columns of table Employee.

Example on number of columns in table 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();

    int numOfColumns = rsmd.getColumnCount();
    System.out.println("Number of columns in Employee table: " + numOfColumns);
                        
    res.close();
    stmt.close();
    con.close();
  }
} 

Database connection is obtained using the standard three statements like Connection and Statement. You can use as well think driver also.

  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.

Pass your comments and suggestions on this tutorial number of columns in table JDBC to improve quality of content.

Leave a Comment

Your email address will not be published.