为什么在尝试对 ResultSet 中检索到的列的值求和时出现错误?

Why do I get an error when trying to sum values of a column retrieved in a ResultSet?

我的代码有什么问题?我认为它在 SQL 中,但我不知道为什么。提前谢谢你

try{
    clsConnect c = new clsConnect();
    Connection conn = c.makeConnection();
    Statement statement = conn.createStatement();
    String display = "SELECT SUM(Amountpaid) from mofficetbl";
    ResultSet rs = statement.executeQuery(display);
    while(rs.next()){
        totalTF.setText(rs.getString("Amountpaid"));
    }
}
catch (SQLException e) {
    JOptionPane.showMessageDialog(null, e);
}

您正在 selecting SUM(amountpaid) 并尝试访问列 amountpaid,但该列实际上并不存在于 ResultSet 尝试 rs.getString(1) 或在 select 中将 SUM 命名为 SELECT SUM(amountpaid) as sum from msofficetbl 然后执行 rs.getString("sum");

当您调用此 select 语句时;返回的列实际上称为 "SUM(amountpaid)" 而不是 amountpaid 因此要么将其别名更改为

"SELECT SUM(Amountpaid) as Amountpaid from mofficetbl"

您还可以这样做:

rs.getString("Sum(Amountpaid)");