Lesson 2: Insert data into the database

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

Adding rows to your database

  1. Add the procedure below to customer.cpp, immediately before the main method:

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

    This procedure carries out 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.

      The commit method is only required when autocommit is turned off. By default, autocommit is enabled, but it may be disabled for better performance, or for multi-operation transactions.

    • 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 after the call to open_conn.

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

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