Search code examples
javasqliteresultset

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.


Solution

  • 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.