MySQL的JDBC判斷查詢結果是否為空以及獲取查詢結果行數的方法
阿新 • • 發佈:2019-01-25
判斷查詢結果是否為空
在JDBC中沒有方法hasNext去判斷是否有下一條資料,但是我們可以使用next方法來代替。 看next方法的官方解釋:-
boolean next() throws
Moves the cursor forward one row from its current position. AResultSet
cursor is initially positioned before the first row; the first call to the methodnext
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
false
, the cursor is positioned after the last row. Any invocation of aResultSet
method which requires a current row will result in aSQLException
being thrown. If the result set type isTYPE_FORWARD_ONLY
, it is vendor specified whether their JDBC driver implementation will returnfalse
SQLException
on a subsequent call tonext
.If an input stream is open for the current row, a call to the method
next
will implicitly close it. AResultSet
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
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();
// 其他程式碼不變