2

I need to get the sum of all values of one column and put it in a textField. i tried the code below but i get an error. - The column name Sum(Price) is not valid.

     String sql="Select Sum(Price) from sold";
                              pst=con.prepareStatement(sql);
                              rs=pst.executeQuery();
                              if(rs.next()){
                                  String sum = rs.getString("Sum(Price)");
                                  textField_2.setText(sum);

com.microsoft.sqlserver.jdbc.SQLServerException: The column name Sum(Price) is not valid.
0

4 Answers 4

4

Use an alias:

 String sql="Select Sum(Price) as sumprice from sold";
                          pst=con.prepareStatement(sql);
                          rs=pst.executeQuery();
                          if(rs.next()){
                              String sum = rs.getString("sumprice");
                              textField_2.setText(sum);

I don't know if the values get converted correctly. The value is a number of some sort. Perhaps you want:

 String sql="Select cast(Sum(Price) as varchar(255)) as sumprice from sold";
0
1

Use an alias for the calculated column

Select Sum(Price) as sum_price from sold
...
String sum = rs.getString("sum_price");
textField_2.setText(sum);
0
0

Use the overload that takes the ordinal column number as the result of an aggregate is nameless by default: rs.getString(1)

0

Try this.

        int sum = 0;
        Statement st = conn.createStatement();
        ResultSet res = st.executeQuery("SELECT SUM(price) FROM sold");
        while (res.next()) {
        int c = res.getInt(1);
        sum = sum + c;

        String str = Integer.toString(sum);
        textField_2.setText(str);

this will work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.