1. 程式人生 > >MySQL的JDBC判斷查詢結果是否為空以及獲取查詢結果行數的方法

MySQL的JDBC判斷查詢結果是否為空以及獲取查詢結果行數的方法

判斷查詢結果是否為空

在JDBC中沒有方法hasNext去判斷是否有下一條資料,但是我們可以使用next方法來代替。 看next方法的官方解釋:
  • boolean next()
          throws 
    Moves the cursor forward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

    When a call to the next

     method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown. If the result set type is TYPE_FORWARD_ONLY, it is vendor specified whether their JDBC driver implementation will return false
     or throw an SQLException on a subsequent call to next.

    If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet object's warning chain is cleared when a new row is read.

    Returns:
    true if the new current row is valid; false if there are no more rows
    Throws:
     - if a database access error occurs or this method is called on a closed result set
翻譯如下:     boolean next() throws SQLException         將當前行從上一行移到下一行。一個 ResultSet的當前行最初指向第一行查詢結果前。當第一次呼叫next的時候,當前行將會指向第一行查詢結果。第二次呼叫就會指向第二行查詢結果,等等。     當呼叫next方法返回false的時候,當前行當前行指向最後一行查詢結果之後。這時候,任何ResultSet 的請求當前行的方法呼叫都會導致SQLException 被丟擲。但如果查詢的結果設定為TYPE_FORWARD_ONLY,next方法在這時候根據實現廠商的不同,可能會返回false也坑能會丟擲SQLException 異常  的警告將會被清楚。 關於的next的開始和結束,可以用下面的圖來解釋:     0->1->2->3->4->0                中間的1, 2, 3, 4是查詢結果     ^                           ^ 開始                          結束 判斷JDBC查詢結果是否為空的正確姿勢:
Statement statement = conn.createStatement();
ResultSet res = statement.executeQuery(selectSql);
if (!res.next()) {
    //res is null
} else {
    // res is not null
}

獲取查詢結果的行數

JDBC並沒有直接提供獲取查詢結果總行數的方法給我們呼叫,為此我們需要使用間接的手段來執行: 第一種方法:
ResultSet res = ...使用某種方法獲取查詢結果
int nRow = 0;
while(res.next()) {
    ++nRow;
}
res.beforeFirst();
// 其他程式碼不變

第二種方法:
ResultSet res = ...使用某種方法獲取查詢結果
res.last();
final int nRow = res.getRow();
res.beforeFirst();
// 其他程式碼不變