1

I want to take the value of total sum of a column and display it in a textfield.

I used this code but it's not working.

public static String invoice() throws SQLException{
          Connection con = connect();
   String query="SELECT SUM(costM) AS totalsum from Meals";
   Statement s =con.createStatement();
   s.execute(query);
   ResultSet rs=s.getResultSet();
     String result =rs.getString("totalsum");
      return result;
     }

 //Method to apply when button clicked
    public void message() throws SQLException{

                textinv.setText(db.invoice());
    }

  • What error do you get ? did you have a look at [this ?](https://stackoverflow.com/questions/21955256/manipulating-an-access-database-from-java-without-odbc) – springe Jun 02 '20 at 13:41

1 Answers1

1

Please see this answer to this issue.

import java.sql.*;  

class TestJava{  
public static void main(String args[]){  
try{  
  Class.forName("com.mysql.jdbc.Driver");  
  Connection con=DriverManager.getConnection(  
   "jdbc:mysql://localhost:3306/shopping_cart","root","root");  

   String query = "select sum(meal_cost) as totalSum from customers";
   Statement stmt=con.createStatement();  
   stmt.executeQuery(query);
   ResultSet rs=stmt.getResultSet();  
   while(rs.next())  
      System.out.println(rs.getString(1));  
      con.close();  
    }
   catch(Exception e){ System.out.println(e);}  
   }  
   }  

Issue, you are facing is due to the cursor is not moved to the specified row. next() function is used for this.

Ruben Helsloot
  • 10,555
  • 5
  • 17
  • 36
jrhamza
  • 714
  • 12
  • 27