Chapter 9. Using Cursors
Prev | Part II. Programming with the Base API | Next

## Chapter 9. Using Cursors

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.

    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());
        }
    }

Prev | Up | Next
Database Record Example | Home | Getting Records Using the Cursor