Java SQL: Statement.hasResultSet()?

前端 未结 2 1325
北荒
北荒 2020-12-04 00:44

My app uses MySQL on one platform and SQLite on another, as such there are differences, such as that when using query like DELETE FROM USERS:

  • On <
2条回答
  •  独厮守ぢ
    2020-12-04 00:56

    When executing a query that returns an unknown amount of results, then you need to use execute(). This method returns a boolean indicating the type of result:

    • true: result is a ResultSet
    • false : result is an update count

    If the result is true, then you use getResultSet() to retrieve the ResultSet, otherwise getUpdateCount() to retrieve the update count. If the update count is -1 it means there are no more results. Note that the update count will also be -1 when the current result is a ResultSet. It is also good to know that getResultSet() should return null if there are no more results or if the result is an update count, so the behavior of SQL Lite to throw an exception seems to be wrong.

    Now if you want to retrieve more results, you call getMoreResults() (or its brother accepting an int parameter). The boolean return value of this method has the same meaning as that of execute(), so false does not mean there are no more results!

    There are only no more results if the getMoreResults() returns false and getUpdateCount() returns -1 (as also documented in the Javadoc)

    Essentially this means that if you want to correctly process all results you need to do something like:

    PreparedStatement pstmt = connection.prepareStatement(...);
    // ...
    boolean result = pstmt.execute();
    while(true)
        if (result) {
            ResultSet rs = pstmt.getResultSet();
            // Do something with resultset ...
        } else {
            int updateCount = pstmt.getUpdateCount();
            if (updateCount == -1) {
                // no more results
                break;
            }
            // Do something with update count ...
        }
        result = pstmt.getMoreResults();
    }
    

提交回复
热议问题