sandbox/morph / Doc / library / bsddb.rst

:mod:`bsddb` --- Interface to Berkeley DB library

The :mod:`bsddb` module provides an interface to the Berkeley DB library. Users can create hash, btree or record based library files using the appropriate open call. Bsddb objects behave generally like dictionaries. Keys and values must be strings, however, so to use other objects as keys or to store other kinds of objects the user must serialize them somehow, typically using :func:`marshal.dumps` or :func:`pickle.dumps`.

The :mod:`bsddb` module requires a Berkeley DB library version from 4.0 thru 4.7.

A more modern DB, DBEnv and DBSequence object interface is available in the :mod:`bsddb.db` module which closely matches the Berkeley DB C API documented at the above URLs. Additional features provided by the :mod:`bsddb.db` API include fine tuning, transactions, logging, and multiprocess concurrent database access.

The following is a description of the legacy :mod:`bsddb` interface compatible with the old Python bsddb module. Starting in Python 2.5 this interface should be safe for multithreaded access. The :mod:`bsddb.db` API is recommended for threading users as it provides better control.

The :mod:`bsddb` module defines the following functions that create objects that access the appropriate type of Berkeley DB file. The first two arguments of each function are the same. For ease of portability, only the first two arguments should be used in most instances.


Beginning in 2.3 some Unix versions of Python may have a :mod:`bsddb185` module. This is present only to allow backwards compatibility with systems which ship with the old Berkeley DB 1.85 database library. The :mod:`bsddb185` module should never be used directly in new code. The module has been removed in Python 3.0. If you find you still need it look in PyPI.

Hash, BTree and Record Objects

Once instantiated, hash, btree and record objects support the same methods as dictionaries. In addition, they support the methods listed below.


>>> import bsddb
>>> db = bsddb.btopen('/tmp/spam.db', 'c')
>>> for i in range(10): db['%d'%i] = '%d'% (i*i)
>>> db['3']
>>> db.keys()
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> db.first()
('0', '0')
('1', '1')
>>> db.last()
('9', '81')
>>> db.set_location('2')
('2', '4')
>>> db.previous()
('1', '1')
>>> for k, v in db.iteritems():
...     print k, v
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
>>> '8' in db
>>> db.sync()