Home > Back-end >  Fetch all values from column in mysql table and sum the values in java
Fetch all values from column in mysql table and sum the values in java

Time:10-05

Name   Id
aa      1
bb      5

I use this to fetch all values from id column

SELECT id FROM name_table;

I want to sum the values in the id column. To be clear, I am making a financial application and want to add up all the money recorded in the msql database

CodePudding user response:

If you want to just get sum of all ID values, then this would work:

SELECT SUM(id) FROM name_table

CodePudding user response:

    int sum = 0;
    while (res.next()) {
    int i = res.getInt(1); or rs.getString("id "); //using column name
    sum = sum   i;
    System.out.println(sum);
 OR
  String q= "SELECT SUM(id) as totalSum FROM tableName";
  PreparedStatement pst = connectio.prepareStatement(q);
  ResultSet rs = pst.executeQuery();
   if (rs.next()) {
    sum = rs.getString("totalSum");
   System.out.print("total sum"   sum);
    } else {
  System.out.print("Query didn't return any results");
  }
  • Related