C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Java programming language

Count number of records available in a MYSQL table using JDBC in java

In this article, we are going to learn how to count number of records available in an MYSQL table using JDBC through java program?
Submitted by Manu Jemini, on October 19, 2017

Prerequisite/recommended:

  1. How to create a table using JDBC in Java?
  2. How to insert records through JDBC in Java?
  3. How to display all records using JDBC in Java?
  4. How to display particular record by a field using JDBC in Java?
  5. How to delete a particular record using JDBC in Java?
  6. How to edit a record using JDBC in Java?
  7. Insert a record with PreparedStatement using JDBC in Java?
  8. How to search record by a field (salary) using JDBC in Java?
  9. Search record by a pattern using JDBC in Java.

Create an object of Connection class and connect to the database.

After that, prepare a MySQL query statement to count number of records available in table named employee, to execute this query, we will create an object of Statement class.

Then, we create an object named smt of Statement class, that will be used to execute query by using executeQuery() method.

Database details:

  • Hostname: localhost
  • Port number: 3306
  • Username: root
  • Password: 123
  • Database name: demo
  • Table name: employees

Java program to count number of records available in MYSQL table using JDBC

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DisplayAll {
	public static void main(String[] args) {
		try{
			Class.forName("com.mysql.jdbc.Driver").newInstance();

			//serverhost = localhost, port=3306, username=root, password=123
			Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","123");

			Statement smt=cn.createStatement();

			//query to count all records from table employee
			String q="Select COUNT(*) from employees";

			//to execute query
			ResultSet rs=smt.executeQuery(q);

			//to print the resultset on console
			System.out.println(rs);
			cn.close();
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
}

Output (In Console)

2








COMMENTS