How to get column count in a ResultSet in JDBC?


You can get the column count in a table using the getColumnCount() method of the ResultSetMetaData interface. On invoking, this method returns an integer representing the number of columns in the table in the current ResultSet object.

//Retrieving the ResultSetMetaData object
ResultSetMetaData rsmd = rs.getMetaData();
//getting the column type
int column_count = rsmd.getColumnCount();

Let us create a table with name employee_data in MySQL database using CREATE statement as shown below −

CREATE TABLE employee_data(
   id INT,
   Name VARCHAR(255),
   DOB date,
   Location VARCHAR(40)
);

Following JDBC program establishes connection with the database, retrieves the ResultSetMetaData object of the employee_data table, and prints the number of columns in it.

Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class NumberOfColumns {
   public static void main(String args[])throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating a Statement object
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("select * from employee_data");
      //Retrieving the ResultSetMetaData object
      ResultSetMetaData rsmd = rs.getMetaData();
      //getting the column type
      int column_count = rsmd.getColumnCount();
      System.out.println("Number of columns in the table : "+column_count);
   }
}

Output

Connection established......
Number of columns in the table : 4

Vikyath Ram
Vikyath Ram

A born rival

Updated on: 30-Jul-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements