Lesson 2: Insert data into the database

The following procedure demonstrates how to add data to a database.

 To add rows to your database
  1. Add the method below to customer.cpp, immediately before the main method:



    static bool do_insert( ULConnection * conn ) 
    {
        ULTable * table = conn->OpenTable( "ULCustomer" );
        if( table == UL_NULL ) {
            _tprintf( "Table not found: ULCustomer\n" );
            return false;
        }
        if( table->GetRowCount() == 0 ) {
            _tprintf( "Inserting one row.\n" );
            table->InsertBegin();
            table->SetString( "cust_name", "New Customer" );
            table->Insert();
            conn->Commit();
        } else {
            _tprintf( "The table has %lu rows\n", table->GetRowCount() );
        }
        table->Close();
        return true;
    }

    This method performs the following tasks.

    • Opens the table using the connection->OpenTable() method. You must open a Table object to carry out operations on the table.

    • If the table is empty, adds a row to the table. To insert a row, the code changes to insert mode using the InsertBegin method, sets values for each required column, and executes an insert to add the row to the database.

    • If the table is not empty, reports the number of rows in the table.

    • Closes the Table object to free resources associated with it.

    • Returns a boolean indicating whether the operation was successful.

  2. Call the do_insert method you have created.

    Add the following line to the main() method, immediately before the call to conn->Close.

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

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