This example adds a new index to a TableDef object in the Biblio.mdb database, makes that index the current index, and invokes the Seek method based on that index. The names of the Field objects created and appended to the Fields collection of the Index object correspond to the names of current fields in the table.
CdbDBEngine dbeng;
CdbRecordset rstPublishers;
CdbDatabase dbsBiblio;
CdbIndex idxPubIDName;
CdbField fldPubID;
CdbField fldName;
COleVariant vYourdon(_T("Yourdon Press"));
dbsBiblio = dbeng.OpenDatabase(_T("Biblio.mdb"));
idxPubIDName = dbsBiblio.TableDefs[_T("Publishers")].CreateIndex(
_T("PubID Name"));
fldPubID = idxPubIDName.CreateField(_T("PubID"));
idxPubIDName.Fields.Append(fldPubID);
fldName = idxPubIDName.CreateField(_T("Name"));
idxPubIDName.Fields.Append(fldName);
idxPubIDName.SetUnique(-1); //True
// Append the new Index to the Indexes collection.
dbsBiblio.TableDefs[_T("Publishers")].Indexes.Append(
idxPubIDName);
//Open the table, look for publisher.
rstPublishers =
dbsBiblio.OpenRecordset(_T("Publishers"),dbOpenTable);
rstPublishers.SetIndex(_T("PubID Name"));
rstPublishers.Seek(_T("="), 1, vYourdon);
if (rstPublishers.GetNoMatch())
{
rstPublishers.MoveFirst();
printf(_T("Not found\n"));
}
else {
printf(_T("Name: %s\n"), rstPublishers.GetName());
}
rstPublishers.Close();
This example sets the index for rstOrders
to the primary key. (PrimaryKey
is the default name of an Index object if the primary key is set in the table's Design view.) Next, it locates the record with a matching key field value of 10,050. Notice that the current index must be set before certain operations, such as the Seek method, can be performed.
CdbDBEngine dbeng;
CdbDatabase dbsNorthwind;
CdbRecordset rstOrders;
dbsNorthwind = dbeng.OpenDatabase(_T("Northwind.mdb"));
rstOrders = dbsNorthwind.OpenRecordset( _T("Orders"),
dbOpenTable);
// Set current index.
rstOrders.SetIndex(_T("PrimaryKey"));
// Locate record.
rstOrders.Seek(_T("="), 1, COleVariant(10500, VT_I4));
rstOrders.Close(); // Close recordset.
dbsNorthwind.Close(); // Close database.