2011-10-18 80 views
0

我的查詢意味着只返回一行(因爲它是通過唯一ID選擇記錄)。如果結果集是空的,我將拋出一個異常,如果它包含多於一行,則拋出異常。恕我直言,在這種情況下,while(rs.next())的結果集看起來並不漂亮。我可以立即獲取結果集中的行數嗎?如何獲取ResultSet包含的行數?

+0

重複。請參閱:[如何獲取java.sql.ResultSet的大小?](http://stackoverflow.com/q/192078) – user272735

回答

3

我不認爲有一種方法可以在單個方法調用中執行此操作。

您可以使用ResultSet的last()方法,然後調用ResultSet的getRow()方法,該方法將根據大小給出ResultSet大小並根據需要拋出異常。

請記得有最終條款關閉所有連接/ DS :)

rs.last(); 

if(rs.getRow() > 1) { 
throw (...); 
} 
3
rs.first(); 
if(!rs.isLast()) 
    throw new Exception(...); 

看來你並不需要知道的行數返回,只是如果有超過1

+0

這就是我實際使用的情況。 – Ivan

0

你試過: java.sql.ResultSet.isBeforeFirst()

來自javadoc: 檢索遊標是否位於此ResultSet對象的第一行之前。

Note:Support for the isBeforeFirst method is optional for ResultSets with a result set type of TYPE_FORWARD_ONLY 

Returns: 
    true if the cursor is before the first row; false if the cursor is at any other position or the result set contains no ro