Moving Around Within a Result Set
2.6.1 Problem
You want to iterate through a result set multiple times, or to move to arbitrary rows within the result.
2.6.2 Solution
If your API has functions that provide these capabilities, use them. If not, fetch the result set into a data structure so that you can access the rows however you please.
2.6.3 Discussion
Some APIs allow you to "rewind" a result set so you can iterate through its rows again. Some also allow you to move to arbitrary rows within the set, which in effect gives you random access to the rows. Our APIs offer these capabilities as follows:
- Perl DBI and Python DB-API don't allow direct positioning within a result set.
- PHP allows row positioning with the mysql_data_seek( ) function. Pass it a result set identifier and a row number (in the range from 0 to mysql_num_rows( )-1). Subsequent calls to row-fetching functions return rows sequentially beginning with the given row. PHP also provides a mysql_result( ) function that takes row and column indexes for random access to individual values within the result set. However, mysql_result( ) is slow and normally should not be used.
- JDBC 2 introduces the concept of a "scrollable" result set, along with methods for moving back and forth among rows. This is not present in earlier versions of JDBC, although the MySQL Connector/J driver does happen to support next( ) and previous( ) methods even for JDBC 1.12.
Whether or not a particular database-access API allows rewinding and positioning, your programs can achieve random access into a result set by fetching all rows from a result set and saving them into a data structure. For example, you can use a two-dimensional array that stores result rows and columns as elements of a matrix. Once you've done that, you can iterate through the result set multiple times or use its elements in random access fashion however you please. If your API provides a call that returns an entire result set in a single operation, it's relatively trivial to generate a matrix. (Perl and Python can do this.) Otherwise, you need to run a row-fetching loop and save the rows yourself.