Search code examples
javamysqlsqlsumjtextfield

Getting the SUM of a column in MySQL table and putting it in JTextField


I am trying to compute for the sum of a column from a MySQL table and putting the result in a JTextField on button-click. Here is the method that computes for the sum:

private void computeTotalUnits(JTextField tf) {
        try {
            st = conn.createStatement();
            sql = "SELECT SUM(no_of_units) AS total_no_of_units FROM schedule;";

            rs = st.executeQuery(sql);

            tf.setText(rs.getString(1));

        } catch(Exception ex) {
            JOptionPane.showMessageDialog(null, ex.toString());
        }
    }

However, I am getting an "SQLException: Before start of result set" upon clicking the button.


Solution

  • Missing rs.next() I guess. See here. Also it is possible that sum is not String. Try to get BigDecimal