Moving Around Within a Result Set

Problem

You want to iterate through a result set multiple times, or to move to arbitrary rows within the result.

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.

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

Get MySQL Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.