我的系统在检索数据库中的某些值时遇到问题。我想获得特定字段中值的摘要。这是我检索值的代码:
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
表中插入新值的代码。但我认为我在第一个查询上有例外。是否正确检索数据?
答案 0 :(得分:3)
您可以使用as name
(别名)来获取它们。实施例
SELECT COUNT(genClientID) as cnt, .........
然后
rs.getString("cnt");
答案 1 :(得分:1)
如果您只想在汇总表中插入聚合值,则可以使用insert select。 这样你就不需要结果集迭代了。 e.g
INSERT INTO summary(id,total,max) SELECT count(id),sum(principal),sum(interest) FROM client_info
答案 2 :(得分: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了。