Chapter 5. Using Cursors

Table of Contents

Opening and Closing Cursors
Getting Records Using the Cursor
Searching for Records
Working with Duplicate Records
Putting Records Using Cursors
Deleting Records Using Cursors
Replacing Records Using Cursors
Cursor Example

Cursors provide a mechanism by which you can iterate over the records in a database. Using cursors, you can get, put, and delete database records. If a database allows duplicate records, then cursors are the only mechanism by which you can access anything other than the first duplicate for a given key.

This chapter introduces cursors. It explains how to open and close them, how to use them to modify databases, and how to use them with duplicate records.

Opening and Closing Cursors

To use a cursor, you must open it using the Database.openCursor() method. When you open a cursor, you can optionally pass it a CursorConfig object to set cursor properties. Currently, the only available property tells the cursor to perform dirty reads. (For a description of dirty reads, see Configuring Dirty Reads).

For example:

import com.sleepycat.je.Environment;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.CursorConfig;
import com.sleepycat.je.Cursor;

...

try {
    myDbEnvironment = new Environment(new File("/export/dbEnv"), 
                                      envConfig);
    Database myDatabase = myDbEnvironment.openDatabase(null, myDbName, 
                                                       null);

    Cursor myCursor = myDatabase.openCursor(null, null);
} catch (DatabaseException dbe) {
    // Exception handling goes here
}

To close the cursor, call the Cursor.close() method. Note that if you close a database that has cursors open in it, then it will complain and close any open cursors for you. For best results, close your cursors from within a finally block.

import com.sleepycat.je.Database;
import com.sleepycat.je.Environment;
import com.sleepycat.je.Cursor;

...
try {
    ...
} catch ... {
} finally {
    if (myCursor != null) {
        myCursor.close();
    }

    if (myDatabase != null) {
        myDatabase.close();
    }

    if (myDbEnvironment != null) {
        myDbEnvironment.close();
    }
}