可能重複:
How to check if resultset has one row or more?executeQuery(String sql)在沒有結果時返回什麼?
什麼會executeQuery(String sql)
回當SQL查詢的結果是零行>?如果它返回一個ResultSet
對象,我們將如何檢測到SQL查詢不返回任何內容。
假定SQL查詢是SELECT
語句。
可能重複:
How to check if resultset has one row or more?executeQuery(String sql)在沒有結果時返回什麼?
什麼會executeQuery(String sql)
回當SQL查詢的結果是零行>?如果它返回一個ResultSet
對象,我們將如何檢測到SQL查詢不返回任何內容。
假定SQL查詢是SELECT
語句。
你檢查了ResultSet's next method。最初,ResultSet的指針指向第一行之前,第一次調用next()返回false意味着ResultSet中沒有數據。請參閱How do I get the size of a ResultSet?,因爲Java中的Resultset沒有直接的size()或length()方法。
具有零行的空結果集,即resultSet.next()
將返回false。
Java中的Resultset沒有size()或length()方法。 – Muse
嗯,我糾正了。 – manurajhada
resultSet的next()方法將光標移動到下一行並返回一個布爾值,指示數據是否已被讀取。通常它與一個while循環一起使用
while (myresultset.next()){ //some statement; }
在您的情況下,如果沒有數據匹配查詢,下一個方法的第一次調用將返回false。
是不是myresultset.first()和myresultset.next()對第一次調用做同樣的工作? –
是的,我想,事件如果取決於實施。試一試。 – jocelyn
它將返回一個ResultSet。使用
boolean hasResult = rs.next();
找出是否有結果行。
如果返回的ResultSet
爲空,那麼在此ResultSet上第一次調用next()
方法的輸出將返回false。
基本上一般的程序是線
ResultSet rs = executeQuery("select ....");
while(rs.next()) {
//do something with the results
}
可以使用rs.getRow()
方法中的東西。
if(rs.getRow() >= 1){
//Has at least 1 result
}
/**
* 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;
它將返回空ResultSet
如果查詢取0的記錄。 最初光標指向結果集之前,當我們呼叫resultset.next()
光標移動到下一個resultset
(迭代器模式)並返回true
如果有任何結果存在,否則它只返回false
。在這種情況下,第一次調用next()
方法返回false
。
你試過嗎?應該返回或空結果集 –
@JigarJoshi我們將如何檢測到返回的對象包含零行? –
['resultSet.next()'](http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/ResultSet。html#next%28%29)在沒有更多數據的情況下返回'false' –