###

Berkeley DB Reference Guide:
  Access Methods

### Storing records with a cursor

The DBcursor->put method stores records into the database using a cursor. In general, DBcursor->put takes a key and inserts the associated data into the database, at a location controlled by a specified flag.

There are several flags that you can set to customize storage:

DB_AFTER
  Create a new record, immediately after the record to which the cursor refers.
DB_BEFORE
  Create a new record, immediately before the record to which the cursor refers.
DB_CURRENT
  Replace the data part of the record to which the cursor refers.
DB_KEYFIRST
  Create a new record as the first of the duplicate records for the supplied key.
DB_KEYLAST
  Create a new record, as the last of the duplicate records for the supplied key.

In all cases, the cursor is repositioned by a DBcursor->put operation to point to the newly inserted key/data pair in the database.

The following is a code example showing a cursor storing two data items in a database that supports duplicate data items:

>     int
>     store(dbp)
>     	DB *dbp;
>     {
>     	DBC *dbcp;
>     	DBT key, data;
>     	int ret;

>     	/*
>     	 * The DB handle for a Btree database supporting duplicate data
>     	 * items is the argument; acquire a cursor for the database.
>     	 */
>     	if ((ret = dbp->cursor(dbp, NULL, &dbcp, 0)) != 0) {
>     		dbp->err(dbp, ret, "DB->cursor");
>     		goto err;
>     	}

>     	/* Initialize the key. */
>     	memset(&key, 0, sizeof(key));
>     	key.data = "new key";
>     	key.size = strlen(key.data) + 1;

>     	/* Initialize the data to be the first of two duplicate records. */
>     	memset(&data, 0, sizeof(data));
>     	data.data = "new key's data: entry #1";
>     	data.size = strlen(data.data) + 1;

>     	/* Store the first of the two duplicate records. */
>     	if ((ret = dbcp->c_put(dbcp, &key, &data, DB_KEYFIRST)) != 0)
>     		dbp->err(dbp, ret, "DB->cursor");

>     	/* Initialize the data to be the second of two duplicate records. */
>     	data.data = "new key's data: entry #2";
>     	data.size = strlen(data.data) + 1;

>     	/*
>     	 * Store the second of the two duplicate records.  No duplicate
>     	 * record sort function has been specified, so we explicitly
>     	 * store the record as the last of the duplicate set.
>     	 */
>     	if ((ret = dbcp->c_put(dbcp, &key, &data, DB_KEYLAST)) != 0)
>     		dbp->err(dbp, ret, "DB->cursor");

>     err:	if ((ret = dbcp->c_close(dbcp)) != 0)
>     		dbp->err(dbp, ret, "DBcursor->close");

>     	return (0);
>     }

Copyright (c) 1996,2007 Oracle. All rights reserved.