I have the following code.The query woks well in mysql but it does not work when integrated with java.Please check the code.Sum is not calculated correctly for all the columns.Please Help .Thanks a lot
import java.io.*;
import java.sql.*;
public class Sum11{
public static void main(String[] args) {
System.out.println("Sum of the specific column!");
Connection con = null;
int sum1=0;
int sum2=0;
int sum3=0;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/prathi","root","mysql");
try{
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT Service_ID,SUM(consumer_feedback) FROM consumer1 group by Service_ID");
while (res.next()){
int data=res.getInt(1);
System.out.println(data);
int c1 = res.getInt(2);
sum1 = sum1+c1;
}
System.out.println("Sum of column " +sum1);
while (res.next()){
int data=res.getInt(1);
System.out.println(data);
int c2 = res.getInt(1);
sum2 = sum2+c2;
}
System.out.println("Sum of column " +sum2);
while (res.next()){
int data=res.getInt(1);
System.out.println(data);
int c3 = res.getInt(1);
sum3 = sum3+c3;
}
System.out.println("Sum of column " +sum3);
}// end of try inner block
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
I have my table as follows.
+------------+--------------+-------------------+
| Service_ID | Service_Type | consumer_feedback |
+------------+--------------+-------------------+
| 31 | Printer | 1 |
| 32 | Printer | -1 |
| 32 | Printer | -1 |
| 32 | Printer | 0 |
| 33 | Printer | 1 |
| 33 | Printer | 1 |
| 31 | Printer | -1 |
| 31 | Printer | -1 |