从Resultset mysql java中检索结果

时间:2017-10-13 14:24:58

标签: java mysql

在Java中

。有谁知道我如何从这个查询中检索数据?我可以为简化查询做到这一点,但我觉得这个案子很混乱:

SELECT (SELECT sum(r2.a) FROM R r2 WHERE year(r2.p) = 
'2015' and month(r2.p) < month(r1.p) ) AS Previous,
            (SELECT sum(r3.a) FROM R r3 WHERE year(r3.p) 
 = '2015' and month(r3.p) > month(r1.p) ) AS Next,
            (SELECT sum(r4.a) FROM R r4 WHERE year(r4.p) 
 = '2015' and month(r4.p) = month(r1.p) ) AS Curr
 FROM R r1
  WHERE YEAR(r1.pickupdate) = '2015';

2 个答案:

答案 0 :(得分:1)

使用声明的别名:AS Curr

ResultSet rs = preparedStatement.executeQuery();

while (rs.next()) {
        Integer curr = rs.getInt("Curr");
        // Do something here
}

答案 1 :(得分:1)

您的语句返回布尔别名Previous,NextM,Cur。 您可以将它们视为整数0或1,就像在另一个答案中一样,但它们仍然是布尔值,并且它们应该如何使用它们。

还要考虑使用 PreparedStatement参数来避免sql注入。

Connection con = null; // ... assuming you already have your connection 

String sql = "SELECT ... WHERE YEAR(r1.pickupdate) = ?";

PreparedStatement pstmt = null;
try
{
    pstmt = con.prepareStatement(sql);

    int year = 2015;
    pstmt.setInt(1, year);

    ResultSet rs = pstmt.executeQuery();
    while (rs.next())
    {

        boolean previous = rs.getBoolean("Previous");
        boolean nextM = rs.getBoolean("NextM");
        boolean curr = rs.getBoolean("Curr");

        // do something here with each record
    }
} finally
{
    // release Statement resources immediately after execution
    try
    {
        pstmt.close();
    } catch (Exception e)
    {
    }
}
// use the same try finally approach for the connection