Lesson 3: Selecting and listing rows from the table

The following procedure retrieves rows from the table and prints them on the command line.

 List rows in the table
  1. Add the method below to customer.cpp immediately after the do_insert method. 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 (cust_id). To order rows in a different way, you can add an index to an UltraLite database and open a table using that index.

    • For each row, the cust_id and cust_name values are written out. The loop carries on until the Next method returns false, which occurs after the final row.

    • Closes the Table object.



    static bool do_select( ULConnection * conn )
    {
        ULTable * table = conn->OpenTable( "ULCustomer" );
        if( table == UL_NULL ) {
            return false;
        }
        ULTableSchema * schema = table->GetTableSchema();
        if( schema == UL_NULL ) {
            table->Close();
            return false;
        }
        ul_column_num id_cid = 
            schema->GetColumnID( "cust_id" );
        ul_column_num cname_cid = 
            schema->GetColumnID( "cust_name" );
        schema->Close();
    
        _tprintf( "\n\nTable 'ULCustomer' row contents:\n" );
        while( table->Next() ) {
            ul_char cname[ MAX_NAME_LEN ];
            table->GetString( cname_cid, cname, MAX_NAME_LEN );
            _tprintf( "id=%d, name=%s \n", (int)table->GetInt(id_cid), cname );
        }
        table->Close();
        return true;
    }
  2. Add the following line to the main method immediately after the call to the insert method:

    do_select(conn);
  3. Compile your application by running nmake.

  4. Run your application by typing customer at a command prompt.