How to Use Different Row Methods to Get Number of Rows in a Table in JDBC?
Last Updated :
13 Jun, 2022
Java supports many databases and for each database, we need to have their respective jar files to be placed in the build path to proceed for JDBC connectivity. For different databases, different jar files are imported to make a connection given below or their built path is supposed to be added for specific databases.
- Types of Database
- SQL
- MySQL: mysql-connector-java-8.0.22
- PostgreSQL
- Oracle: ojdbc14.jar
- Microsoft SQL server
- NoSQL
- MongoDB: mongo-java-driver-3.12.7
- BigTable
- Redis
- Progress
- Cassandra
- CouchDB
- RavenDB
Illustration: SQL and Oracle databases are mostly used for illustration. Here SQL database is taken into consideration. Here Table_Name is Table name. Here it will take all columns and count the rows.
Input: Existing data in the table is shown in the below image
- SQL server used: sqljdbc4.jar
- SQL table used

CREATE TABLE `studentsdetails` (
`id` int(6) unsigned NOT NULL,
`Name` varchar(50) NOT NULL,
`caste` varchar(10) NOT NULL,
`NeetMarks` int(11) NOT NULL,
`gender` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Approaches:
A less efficient way of creating a query
select count(*) from Table_Name;
A more efficient way of creating a query
select count(1) from Table_Name;
This query will take the first column and count the rows. As mostly, the Primary key is the first column, it is ideal enough as the Primary key is always unique and not null.
Example 1 | Example 2 |
---|
It will give only one row as output containing a number of rows. Hence, 'resultset' will be kept as next itself. | select * will bring the whole resultset and the cursor is forced to move last and finally 'resultset.getRow()' method will give the number of rows. |
It is more efficient | It is comparatively less efficient |
Example 1: To get the number of rows in a table in JDBC by selecting count(1) from 'studentsdetails' will provide the result as 5.
Java
/* Java Program to use different row methods
to get no of rows in a table in JDBC */
// Step 1: Importing database libraries
import java.sql.*;
// Only main class- GFG is shown
// connection class object is used
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Initially connection is assigned Null valued
Connection con = null;
ResultSet res = null;
// Try block to check exceptions
try {
/* Step 2: Load and register drivers or
relevant jars in build path of project */
// Here- 'mysql-connector-java-8.0.22'
// is used using Class.forNmae() method
Class.forName("com.mysql.cj.jdbc.Driver");
/* Step 3: Establish a connection using
DriverManager method */
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test?serverTimezone=UTC",
"root", "");
// Try block to check exceptions
try {
Statement st = con.createStatement();
/* This query will take first column and
count the rows. As mostly, Primary key is
the first column, it is ideal enough as
Primary key is always unique and not
null */
/* Step 4: Create a statement */
/* Alias name is used as NumberOfRows
for COUNT(1) Moving the cursor to the
last row */
res = st.executeQuery(
"SELECT COUNT(1) as NumberOfRows FROM "
+ "studentsdetails");
/* Step 5: Execute the query */
res.next();
/* Step 6: Process the results */
System.out.println(
"MySQL Table - studentsdetails contains "
+ res.getInt("NumberOfRows") + " rows");
}
// Catch block to handle exceptions
catch (SQLException s) {
// Message to be displayed if SQLException
// occurs
System.out.println(
"SQL statement is not executed!");
}
}
catch (Exception e) {
/* Displaying line where exception occurred using
method returning line number in code */
e.printStackTrace();
}
finally {
// Step 7: Closing the connection
res = null;
con = null;
}
}
}
Output:

Example 2: To get the number of rows in a table in JDBC
Java
/* Step 1: Importing Database libraries */
import java.sql.*;
/* Only main class-GFG is shown
Connection class of JDBC is not shown.
Object of connection class is used */
public class GFG {
// Main driver method
public static void main(String[] args)
{
/* Objects are assigned null
before any execution */
// Connection class objects
Connection con = null;
ResultSet res = null;
// Try block to check exceptions
try {
/* Step 2: Load and register drivers
or relevant jars in build path of project */
// Driver used- 'mysql-connector-java-8.0.22'
// Loading and register drivers
// using Class.forname() method
Class.forName("com.mysql.cj.jdbc.Driver");
/* Step 3: Create a connection */
// using DriverManager
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test?serverTimezone=UTC",
"root", "");
// Display message when connection
// is successfully established
System.out.println(
"Connection is established");
// Try block to check exceptions
try {
/* In order to avoid Result set type is
TYPE_FORWARD_ONLY */
Statement st = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
/* Query takes first column and
count the rows. As mostly, Primary key is
the first column, it is ideal enough as
Primary key is always unique & not null.
*/
/* Step 4: Creating the statement */
res = st.executeQuery("SELECT * FROM "
+ "studentsdetails");
/* Step 5: Execute the statements */
// Moving the cursor to the last row
res.last();
/* Step 6: Process the results */
System.out.println(
"MySQL Table - studentsdetails contains "
+ res.getRow() + " rows");
}
// Catch block to handle exceptions
catch (SQLException s) {
// Exception handled if it is SQL based
System.out.println(
"SQL statement is not executed!"
+ s.getMessage());
}
}
catch (Exception e) {
// Exception handled here if it is generic
// program based
e.printStackTrace();
}
finally {
// Step 7: Closing the connection
res = null;
con = null;
}
}
}
Output:

Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read