JDBC: Rows Count Example


 

JDBC: Rows Count Example

In this section, You will learn how to count number of rows in a table using JDBC API.

In this section, You will learn how to count number of rows in a table using JDBC API.

JDBC: Rows Count Example

In this section, You will learn how to count number of rows in a table using JDBC API.

Counting number of rows -

To count the number of rows of a table we use COUNT(*). It will returns the number of rows in a specified table, doesn't matter they contain NULL values.
We write COUNT(*) with select statement and call method executeQuery(sql) whose result is stored in ResultSet object.

Your query -
String sql = "SELECT count(*) FROM student";
rs = statement.executeQuery(sql);

Example : In this example we are counting the number of rows of student table.

package jdbc;

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

class CountRowsExample {
	public static void main(String[] args) {
		System.out.println("Row Count Example...");
		Connection con = null;
		Statement statement = null;
		ResultSet rs = null;
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "students";
		String driverName = "com.mysql.jdbc.Driver";
		String userName = "root";
		String password = "root";
		try {
			Class.forName(driverName);

			// Connecting to the database
			con = DriverManager.getConnection(url + dbName, userName, password);
			try {
				statement = con.createStatement();

				// counting rows
				String sql = "SELECT count(*) FROM student";
				rs = statement.executeQuery(sql);
				rs.next();
				System.out.println("Number of rows in student table : "
						+ rs.getInt(1));
			} catch (SQLException e) {
				System.out.println("Table doesn't exist.");
			}
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output :

Row Count Example...
Number of rows in student table : 4

Ads