Chapter 9. Using Cursors

Table of Contents

Opening and Closing Cursors
Getting Records Using the Cursor
Disk Ordered Cursors
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. The cursor properties that you can set allows you to determine whether the cursor will perform committed or uncommitted reads. See the Berkeley DB, Java Edition Getting Started with Transaction Processing guide for more information.

For example:

package je.gettingStarted;
    
import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;

import java.io.File;

...
Environment myDbEnvironment = null;
Database myDatabase = null;
Cursor myCursor = null;

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

    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 throw an exception and close any open cursors for you. For best results, close your cursors from within a finally block. However, it is recommended that you always close all cursor handles immediately after their use to ensure concurrency and to release resources such as page locks.

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

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

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

        if (myDbEnvironment != null) {
            myDbEnvironment.close();
        }
    } catch(DatabaseException dbe) {
        System.err.println("Error in close: " + dbe.toString());
    }
}