mabuzer
mabuzer

Reputation: 6707

Best Approach to get `ResultSet` size

What's the best approach (Speed) to get RestultSet size in Java, so I can store them in Array, which I need to specify it's size before creation, I've found the following:

  1. Call ResultSet.last(), then call ResultSet.getRow().
  2. Iterate through ResultSet using next() while having a counter.
  3. Execute a SELECT COUNT query for any given query.
  4. Execute FOUND_ROWS() after each query.
  5. Read results into ArrayList then converting it to Array.

Upvotes: 0

Views: 119

Answers (1)

publysher
publysher

Reputation: 11372

The only option would be #5: put the data in an ArrayList and use toArray to extract an array.

Options #3 and #4 (extra queries) are a bad idea, speed-wise, because database queries have an inherent latency, no matter how fast your database is.

Options #1 and #2 are just a bad idea; ResultSet is meant to be iterated in one direction. While you can move the cursor in other directions, most JDBC drivers will not perform too well doing this.

Finally, you should really reconsider returning an array. Java arrays are great for creating new collection data types and high-performant libraries, but for most business purposes they are inferior to the standard Collections API.

Upvotes: 2

Related Questions