2012-06-13 66 views
4

可能重複:
How to check if resultset has one row or more?executeQuery(String sql)在沒有結果時返回什麼?

什麼會executeQuery(String sql)回當SQL查詢的結果是零行>?如果它返回一個ResultSet對象,我們將如何檢測到SQL查詢不返回任何內容。

假定SQL查詢是SELECT語句。

+0

你試過嗎?應該返回或空結果集 –

+0

@JigarJoshi我們將如何檢測到返回的對象包含零行? –

+0

['resultSet.next()'](http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/ResultSet。html#next%28%29)在沒有更多數據的情況下返回'false' –

回答

1

具有零行的空結果集,即resultSet.next()將返回false。

+0

Java中的Resultset沒有size()或length()方法。 – Muse

+0

嗯,我糾正了。 – manurajhada

4

resultSet的next()方法將光標移動到下一行並返回一個布爾值,指示數據是否已被讀取。通常它與一個while循環一起使用

while (myresultset.next()){ //some statement; } 在您的情況下,如果沒有數據匹配查詢,下一個方法的第一次調用將返回false。

+0

是不是myresultset.first()和myresultset.next()對第一次調用做同樣的工作? –

+0

是的,我想,事件如果取決於實施。試一試。 – jocelyn

2

它將返回一個ResultSet。使用

boolean hasResult = rs.next();

找出是否有結果行。

0

如果返回的ResultSet爲空,那麼在此ResultSet上第一次調用next()方法的輸出將返回false。

基本上一般的程序是線

ResultSet rs = executeQuery("select ...."); 
while(rs.next()) { 
    //do something with the results 
} 
-1

可以使用rs.getRow()方法中的東西。

if(rs.getRow() >= 1){ 
     //Has at least 1 result 
    } 

Source:

/** 
    * Retrieves the current row number. The first row is number 1, the 
    * second number 2, and so on. 
    * <p> 
    * <strong>Note:</strong>Support for the <code>getRow</code> method 
    * is optional for <code>ResultSet</code>s with a result 
    * set type of <code>TYPE_FORWARD_ONLY</code> 
    * 
    * @return the current row number; <code>0</code> if there is no current row 
    * @exception SQLException if a database access error occurs 
    * or this method is called on a closed result set 
    * @exception SQLFeatureNotSupportedException if the JDBC driver does not support 
    * this method 
    * @since 1.2 
*/ 
     int getRow() throws SQLException; 
0

它將返回空ResultSet如果查詢取0的記錄。 最初光標指向結果集之前,當我們呼叫resultset.next()光標移動到下一個resultset(迭代器模式)並返回true如果有任何結果存在,否則它只返回false。在這種情況下,第一次調用next()方法返回false