Java Project JSP JDBC Java Program Core Java Demo MORE

How to Count number of rows in a table using JSP


For Counting number of rows in a table SQL Count() function is used.

Here in this example we will count how many rows available in students_data table.

SQL COUNT() Syntax

SELECT COUNT(column_name)
FROM table_name
WHERE condition;

In this example we count how many Row in the students_data table.

count-rows.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Count Rows JSP</title>
</head>
<body>
<%
try
{
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","");     
    Statement st=con.createStatement();
    String strQuery = "SELECT COUNT(*) FROM students_data";
    ResultSet rs = st.executeQuery(strQuery);

    String Countrow="";
      while(rs.next()){
      Countrow = rs.getString(1);
      out.println("Total Row :" +Countrow);
       } 
    }
catch (Exception e){
    e.printStackTrace();
  }
  %>
</body>
</html>
RollNo Name Address ContactNo
1 Divya Mumbai 9437911966
2 Hritika Pune 9887454545
3 Amit Delhi 7766888888

SQL Query

SELECT COUNT(*)
FROM students_data;

Output

3