2017-10-13 74 views
0

in 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'; 

回答

1

使用聲明別名:AS Curr

ResultSet rs = preparedStatement.executeQuery(); 

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

謝謝,你救了我! –

+0

很高興聽到:)請標記正確的答案讓其他人重複使用。 –

1

你的語句返回布爾別名上,NextM,薑黃素。 你可以把它們當作整數0或1,就像在其他答案中一樣,但它們仍然是布爾值和imo,這就是它們應該如何使用的。

還要考慮使用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