1

我的系统在检索数据库中的某些值时遇到问题。我想获得特定字段中值的摘要。这是我检索值的代码:

public void insertToClientSummary(){
    sql = "SELECT COUNT(genClientID), SUM(principal), SUM(interest), SUM(totalPayment), SUM(totalBal) FROM client_info";
    try {
        stmt = conn.prepareStatement(sql);
        rs = stmt.executeQuery();
        String titles[] = new String [4];
        titles[0] = "Total Clients";
        titles[1] = "Total Loan Book";
        titles[2] = "Total Interests";
        titles[3] = "Total Payment";
        titles[4] = "Total Balance";
        rs.next();
        for (int ctr=0;ctr<=5;ctr++){
            String sql2 = "INSERT INTO client_summary (title, sumValues) VALUES ('"+titles[ctr]+"','')";
            PreparedStatement stmt2 = conn.prepareStatement(sql2);
            stmt2.executeUpdate();
            ctr++;
            sql = "UPDATE client_summary SET sumValues = '"+String.valueOf(rs.getDouble(ctr))+"'";
            stmt = conn.prepareStatement(sql);
            stmt.executeUpdate();
            ctr--;
        }
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, "Client Summary Query Exception");
    }
}

顺便说一句,我还包括了用于在所述client_summary表中插入新值的代码。但我认为我在第一次查询时遇到了异常。对正确检索数据有任何想法吗?

4

3 回答 3

3

您可以使用as name(alias) 来获取它们。例子

SELECT COUNT(genClientID) as cnt, .........

然后

   rs.getString("cnt");
于 2013-01-22T04:29:42.160 回答
1

如果您只想在汇总表中插入聚合值,则可以使用 insert select。这样你就不需要结果集迭代。例如

INSERT INTO summary(id,total,max) SELECT count(id),sum(principal),sum(interest) FROM client_info
于 2013-01-22T05:18:56.380 回答
0

这个解决方案对我不起作用。我不知道我在 SQL 查询中是否有问题,但如果我在数据库上运行它,它会返回正确的值。

SELECT ((SUM(Y1) * 20) / 60) as heat FROM logger.AcondData where (time > '2013-10-12 0:0:0' and time < '2013-10-12 23:59:59') and Y1 = 1 and Y8 = 0;

这里是从 ResultSet 中获取的。

java.sql.PreparedStatement preparedStatement = mConnection.prepareStatement(query);
ResultSet resultSet = preparedStatement.executeQuery();

while (resultSet.next())
{
    printWriter.println("<h1>Heating time: " + resultSet.getString("heat") + " minut");
}

Edit1:如果我删除最后两个条件,它会起作用。

SELECT ((SUM(Y1) * 20) / 60) as heat FROM logger.AcondData where (time > '2013-10-12 0:0:0' and time < '2013-10-12 23:59:59');

Y1 和 Y8 是 TINYINT(1)

Edit2:现在它的工作,看起来问题出在数据库数据中。从远程数据库导入数据后就OK了。

于 2013-10-12T20:59:46.880 回答