简体   繁体   中英

Get the size of a ResultSet in Java for SQLite

I'm attempting to grab the size of a ResultSet. Now because I'm using SQLite, and SQLite only supports TYPE_FORWARD_ONLY cursors I'm trying to figure out how to grab it's size without throwing an error. This wont work:

int size = 0;    
rs.last();
size = rs.getRow();

Nor can I use a prepared statement to change the cursor to scroll-able. Are Is there anyway to get the size?

I've also tried creating a while loop method to handle this and it still doesn't seem to to work

 public static int getResultSetSize(ResultSet rs) throws SQLException{
     int size = 0;

     while(rs.next()){
         size++;
     }

     return size;
 }

Any help would be appreciated.

EDIT:

I've tried the following with no success

ResultSet rs = DBHelpers.getResultSet("SELECT COUNT(*) FROM USERS;");
    int count = 0;

    try {
        count =rs.getInt(0) ;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

The helper method for that is as follow:

 public static ResultSet getResultSet(String sql){
     ResultSet rs = null;;
        try (Statement stmt  = conn.createStatement()){
              rs = stmt.executeQuery(sql);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
            return null;
        }
        return rs;
    }

Conn is static connection variable initialized elsewhere in the program to point to the proper database and it has not caused any problems.

You should map your result to an entity. Create a list of those entities, and then simply get the size of the list.

If you want the size and the size only, then simply make a query to return a count of the result of your original query.

The column begins with index 1. Try this...

Removes the semicolon from your query

ResultSet rs = DBHelpers.getResultSet("SELECT COUNT(*) FROM USERS");

And then

while (rs.next()) {
            System.out.println(rs.getInt(1));
        }

Instead of

count =rs.getInt(0);

Do a count on the database for the same query... SELECT Count(*) your query... .

Run that before you do your query and you should have the size of your result set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM