Sunday, September 07, 2008

Counting rows

After a bit of theory on how to open a base table cursor and on the SQL Compact OLE DB limitations, let's take a first look at how to use the IRowset interface to count table rows. To illustrate this, I pulled together a sample (RowCount) that counts the rows of all tables in a sample database (the good old Northwind database). To run the sample, copy the SDF file (depending on your installed version of SQL Compact: test20.sdf, test30.sdf or test35.sdf) to your device's root and execute the code (it's more interesting to step through the debugger).

In this sample, I introduce two new classes: CTable and CRowset. The CTable class encapsulates the IOpenRowset interface and will be used later to store schema information about a table. The CRowset class encapsulates the IRowset interface and in its present incarnation allows only to scroll forward through the row collection, no data is read. To count rows, the sample application calls the MoveFirst and MoveNext methods on an open rowset. 

These methods still have a very simple implementation but already illustrate the fact that only one row handle is returned by the provider. Also, note that the row handle must be released before the cursor moves to the next row. By combining a row handle and an accessor, our code will be able to fetch data. Right now this is not needed: we just want to count rows, so loading them into memory is a wasteful operation.

The next sample will be a bit more complex as it will open a base table cursor, create all the necessary bindings (no blobs yet) and then display the table data on a list view.

No comments: