How to count rows – count (*) and Java

The SQL Count() function returns the number of rows in a table. Using this you can get the number of rows in a table.

select count(*) from TABLE_NAME;

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

CREATE TABLE cricketers_data(
   First_Name VARCHAR(255),
   Last_Name VARCHAR(255),
   Date_Of_Birth date,
   Place_Of_Birth VARCHAR(255),
   Country VARCHAR(255),

Now, we will insert 5 records in cricketers_data table using INSERT statements −

insert into cricketers_data values('Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');
insert into cricketers_data values('Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');
insert into cricketers_data values('Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');
insert into cricketers_data values('Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');
insert into cricketers_data values('Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');

Following JDBC program establishes connection with MySQL and displays the number of rows in the table named cricketers_data.


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Count_Example {
   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 the Statement object
      Statement stmt = con.createStatement();
      //Query to get the number of rows in a table
      String query = "select count(*) from Cricketers_Data";
      //Executing the query
      ResultSet rs = stmt.executeQuery(query);
      //Retrieving the result;
      int count = rs.getInt(1);
      System.out.println("Number of records in the cricketers_data table: "+count);


Connection established......
Number of records in the cricketers_data table: 5
Vikyath Ram
Vikyath Ram

A born rival