UltraLite C++ User's Guide
Tutorial: An Introductory Application
This lesson shows you how to add data to the database.
To add rows to your database
Add procedure below to customer.cpp, immediately before the main method. This procedure carries out the following tasks:
Opens the table. You must open a Table object to carry out any operations on the table. To obtain a Table object, use the connection->OpenTable() method.
Obtains identifiers for some of the columns of the table. The other columns in the table can accept NULL values or have a default value; in this tutorial only required values are specified.
If the table is empty, adds two rows. To insert each row, the code sets the mode to insert mode using InsertBegin, sets values for each required column, and executes an insert to add the rows to the database.
The commit method is not strictly needed here, as the default mode for applications is to commit operations after each insert. It has been added to the code to emphasize that if you turn off autocommit behavior (for better performance, or for multi-operation transactions) you must commit a change for it to be permanent.
If the table is not empty, reports the number of rows in the table.
Closes the Table object.
Returns a boolean indicating whether the operation was completed.
bool do_insert( Connection * conn ) { Table * table = conn->OpenTable( UL_TEXT("customer") ); if( table == NULL ) { return false; } if( table->GetRowCount() == 0 ) { _tprintf( UL_TEXT("Inserting two rows.\n") ); table->InsertBegin(); table->Set( UL_TEXT("fname"), UL_TEXT("Penny") ); table->Set( UL_TEXT("lname"), UL_TEXT("Stamp") ); table->Insert(); CHECK_ERROR(); table->InsertBegin(); table->Set( UL_TEXT("fname"), UL_TEXT("Gene") ); table->Set( UL_TEXT("lname"), UL_TEXT("Poole") ); table->Insert(); CHECK_ERROR(); conn->Commit(); CHECK_ERROR(); } else { _tprintf( UL_TEXT("The table has %lu rows\n"), table->GetRowCount() ); } table->Release(); return true; }
Add the following line to the main()
method, immediately after the call to the Customer constructor:
do_insert(conn);
Compile and run your application, as in Lesson 1: Connect to the database.
The first time you run the application, it prints the following messages:
Connected to an existing database. Inserting two rows. id=1, name=Penny Stamp id=2, name=Gene Poole
Subsequent times, it prints the following messages:
Connected to an existing database. The table has 2 rows.