Java Project JSP JDBC Java Program Core Java Demo MORE

How to Get sum of MySQL column in JSP


For get sum of MySQL SUM() function is used.

Here in this example we will calculate the total run Virat score in three match.

SQL COUNT() Syntax

SELECT SUM(column_name)
FROM table_name;

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>Sum of column 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 SUM(Run) FROM cricket_score";
    ResultSet rs = st.executeQuery(strQuery);

    String Countrun="";
      while(rs.next()){
      Countrun = rs.getString(1);
      out.println("Total Run :" +Countrun);
       } 
    }
catch (Exception e){
    e.printStackTrace();
  }
  %>
</body>
</html>
MatchNo Name Run Wicket
1 Virat 78 1
2 Virat 82 2
3 Viart 50 0

SQL Query

		SELECT SUM(Run)
                FROM cricket_score;
    

Output

210