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

判斷查詢結果是否為空

在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:
    SQLException – 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(); // 其他代碼不變
? 版權聲明
THE END
喜歡就支持一下吧
點贊11 分享