Putting Records Using Cursors

You can use cursors to put records into the database. JE's behavior when putting records into the database differs depending on whether the database supports duplicate records. If duplicates are allowed, its behavior also differs depending on whether a comparator is provided for the database. (Comparators are described in Using Comparators).

Note that when putting records to the database using a cursor, the cursor's position in the database is left unchanged. For example, suppose your database contains keys A, B, C. Also, suppose that you position your cursor to record B, and you then put record D to the database. In this case, your cursor remains positioned at record B even while record D is inserted into the database in the position determined by the sort order set for the database.

You can use the following methods to put records to the database:

For example:

import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.Database;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.OperationStatus; 

...
  
// Create the data to put into the database
String key1str = "My first string";
String data1str = "My first data";
String key2str = "My second string";
String data2str = "My second data";
String data3str = "My third data";

try {
    DatabaseEntry key1 = new DatabaseEntry(key1str.getBytes("UTF-8"));
    DatabaseEntry data1 = new DatabaseEntry(data1str.getBytes("UTF-8"));
    DatabaseEntry key2 = new DatabaseEntry(key2str.getBytes("UTF-8"));
    DatabaseEntry data2 = new DatabaseEntry(data2str.getBytes("UTF-8"));
    DatabaseEntry data3 = new DatabaseEntry(data3str.getBytes("UTF-8"));

    // Open a cursor using a database handle
    Cursor cursor = myDatabase.openCursor(null, null);

    // Assuming an empty database.

    OperationStatus retVal = cursor.putKeyFirst(key1, data1); // SUCCESS
    retVal = cursor.putKeyFirst(key2, data2); // SUCCESS
    retVal = cursor.putKeyFirst(key2, data3); // SUCCESS if dups allowed, 
                                              // KEYEXISTS if not.    
                                              
} catch (Exception e) {
    // Exception handling goes here
}