bsddb for beginners?

Skip Montanaro skip at pobox.com
Tue Mar 5 09:36:35 EST 2002


(Apologies for the long-winded reply.  I've been answering questions on
python-help for too long I guess.  Just jump to the end for the spoiler. ;-)

    A> I want to get into databases, but most of the tuts around seem to be
    A> over my head.

    >>> import bsddb
    >>> db = bsddb.btopen('spam.db', 'c')

These two lines should be pretty straightforward.  Import the necessary
module and create a bsddb btree file associated on disk with spam.db.

    >>> for i in range(10): db['%d'%i] = '%d'% (i*i)

Let's restructure this a bit:

    for i in range(10):
        key = '%d' % i
        val = '%d' % (i*i)
        db[key] = val

The first line loops i over the integers 0 through 9 inclusive.  The last
line associates val with key in the database file.   Most database file
packages like bsddb (and dumbdbm and dbm) require the keys and values to be
strings.   If the code was

    for i in range(10):
        key = i
        val = i*i
        db[key] = val

it would make more sense, as it would be just like a dictionary, however it
would raise an error.  The assignments

    key = '%d' % i
    val = '%d' % (i*i)

simply convert i and i*i to strings.  In this case you could also use

    key = str(i)
    val = str(i*i)

or

    key = `i`
    val = `i*i`

When the left-hand argument to the % operator is a string, a new string is
produced by interpolating the right-hand argument(s) according to the format
specifiers in the string.  %d tells the format operator to treat the
corresponding argument as an integer.  For complete details of string
formatting, check out

    http://www.python.org/doc/current/lib/typesseq-strings.html

    A> Also, do I take it that the Berkely System comes with Python 2.2, and
    A> therefore I don't need to download anything else? Or is bsddb merely
    A> an interface for the Berkely System?

The bsddb module is simply a wrapper around the Berkeley DB library.  It
comes with Python, but Berkeley DB comes probably from your OS vendor.

-- 
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)




More information about the Python-list mailing list