UltraLite C++ User's Guide
Tutorial: An Introductory Application
This lesson retrieves rows from the table, and prints them on the command line. It shows how to loop over the rows of a table.
To list the rows in the table
Add the method below to customer.cpp. This method carries out the following tasks:
Opens the Table object.
Retrieves the column identifiers.
Sets the current position before the first row of the table.
Any operations on a table are carried out at the current position. The position may be before the first row, on one of the rows of the table, or after the last row. By default, as in this case, the rows are ordered by their primary key value (id). To order rows in a different way (alphabetically by name, for example), you can add an index to an UltraLite database and open a table using that index.
For each row, the id and name are written out. The loop carries on until Next returns false, which happens after the final row.
Closes the Table object.
bool do_select( Connection * conn ) { Table * table = conn->OpenTable( UL_TEXT("customer") ); if( table == NULL ) { return false; } TableSchema * schema = table->GetSchema(); if( schema == NULL ) { table->Release(); return false; } ul_column_num id_cid = schema->GetColumnID( UL_TEXT("id") ); ul_column_num fname_cid = schema->GetColumnID( UL_TEXT("fname") ); ul_column_num lname_cid = schema->GetColumnID( UL_TEXT("lname") ); schema->Release(); while( table->Next() ){ ul_char fname[ MAX_NAME_LEN ]; ul_char lname[ MAX_NAME_LEN ]; table->Get( fname_cid ).GetString( fname, MAX_NAME_LEN ); table->Get( lname_cid ).GetString( lname, MAX_NAME_LEN ); _tprintf( "id=%d, name=%s %s\n", (int)table->Get( id_cid ), fname, lname ); } table->Release(); return true; }
Add the following line to the main()
method, immediately after the call to the insert method:
do_select(conn);
Compile and run your application, as in Lesson 1: Connect to the database.
The application prints the following message:
Connected to an existing database. The table has 2 rows. id= 1, name= Gene Poole id= 2, name= Penny Stamp