Library Version 12.1.6.0

Using Secondary Cursors
Prev | Chapter 10. Secondary Databases | Next

## Using Secondary Cursors

Just like cursors on a primary database, you can use secondary cursors to iterate over the records in a secondary database. Like normal cursors, you can also use secondary cursors to search for specific records in a database, to seek to the first or last record in the database, to get the next duplicate record, to get the next non-duplicate record, and so forth. For a complete description on cursors and their capabilities, see Using Cursors.

However, when you use secondary cursors:

- Any data returned is the data contained on the primary database record referenced by the secondary record.

- `SecondaryCursor.getSearchBoth()` and related methods do not search based on a key/data pair. Instead, you search based on a secondary key and a primary key. The data returned is the primary data that most closely matches the two keys provided for the search.

For example, suppose you are using the databases, classes, and key creators described in Implementing Key Creators . Then the following searches for a person's name in the secondary database, and deletes all secondary and primary records that use that name.

    package je.gettingStarted;

    import com.sleepycat.je.DatabaseEntry;
    import com.sleepycat.je.LockMode;
    import com.sleepycat.je.OperationStatus;
    import com.sleepycat.je.SecondaryDatabase;
    import com.sleepycat.je.SecondaryCursor;

    ...
    try {
        // Database and environment opens omitted for brevity
        ...

        String secondaryName = "John Doe";
        DatabaseEntry secondaryKey =
            new DatabaseEntry(secondaryName.getBytes("UTF-8"));

        DatabaseEntry foundData = new DatabaseEntry();

        SecondaryCursor mySecCursor =
            mySecondaryDatabase.openSecondaryCursor(null, null);

        OperationStatus retVal = mySecCursor.getSearchKey(secondaryKey,
                                                          foundData,
                                                          LockMode.DEFAULT);
        while (retVal == OperationStatus.SUCCESS) {
            mySecCursor.delete();
            retVal = mySecCursor.getNextDup(secondaryKey,
                                            foundData,
                                            LockMode.DEFAULT);
        }
    } catch (Exception e) {
        // Exception handling goes here
    }

Prev | Up | Next
Deleting Secondary Database Records | Home | Database Joins