Berkeley DB Reference Guide:
Access Methods
PrevRefNext

Retrieving records with a cursor

The DBcursor->get method retrieves records from the database using a cursor. The DBcursor->get method takes a flag which controls how the cursor is positioned within the database and returns the key/data item associated with that positioning. Similar to DB->get, DBcursor->get may also take a supplied key and retrieve the data associated with that key from the database. There are several flags that you can set to customize retrieval.

Cursor position flags
DB_FIRST, DB_LAST DB_NEXT, DB_PREV DB_NEXT_DUP DB_NEXT_NODUP, DB_PREV_NODUP DB_CURRENT
Retrieving specific key/data pairs
DB_SET DB_SET_RANGE DB_GET_BOTH DB_GET_BOTH_RANGE
Retrieving based on record numbers
DB_SET_RECNO DB_GET_RECNO
Special-purpose flags
DB_CONSUME DB_RMW

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

The following is a code example showing a cursor walking through a database and displaying the records it contains to the standard output:

int
display(database)
	char *database;
{
	DB *dbp;
	DBC *dbcp;
	DBT key, data;
	int close_db, close_dbc, ret;

close_db = close_dbc = 0;

/* Open the database. */ if ((ret = db_create(&dbp, NULL, 0)) != 0) { fprintf(stderr, "%s: db_create: %s\n", progname, db_strerror(ret)); return (1); } close_db = 1;

/* Turn on additional error output. */ dbp->set_errfile(dbp, stderr); dbp->set_errpfx(dbp, progname);

/* Open the database. */ if ((ret = dbp->open(dbp, NULL, database, NULL, DB_UNKNOWN, DB_RDONLY, 0)) != 0) { dbp->err(dbp, ret, "%s: DB->open", database); goto err; }

/* Acquire a cursor for the database. */ if ((ret = dbp->cursor(dbp, NULL, &dbcp, 0)) != 0) { dbp->err(dbp, ret, "DB->cursor"); goto err; } close_dbc = 1;

/* Initialize the key/data return pair. */ memset(&key, 0, sizeof(key)); memset(&data, 0, sizeof(data));

/* Walk through the database and print out the key/data pairs. */ while ((ret = dbcp->c_get(dbcp, &key, &data, DB_NEXT)) == 0) printf("%.*s : %.*s\n", (int)key.size, (char *)key.data, (int)data.size, (char *)data.data); if (ret != DB_NOTFOUND) { dbp->err(dbp, ret, "DBcursor->get"); goto err; }

err: if (close_dbc && (ret = dbcp->c_close(dbcp)) != 0) dbp->err(dbp, ret, "DBcursor->close"); if (close_db && (ret = dbp->close(dbp, 0)) != 0) fprintf(stderr, "%s: DB->close: %s\n", progname, db_strerror(ret)); return (0); }


PrevRefNext

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