You are here

Databases

8 September, 2015 - 10:43

A database is a file that is organized for storing data. Most databases are organized like a dictionary in the sense that they map from keys to values. The biggest difference is that the database is on disk (or other permanent storage), so it persists after the program ends.

The module anydbm provides an interface for creating and updating database files. As an example, I’ll create a database that contains captions for image files.

Opening a database is similar to opening other files:

>>> import anydbm>>> db = anydbm.open('captions.db', 'c')

The mode 'c' means that the database should be created if it doesn’t already exist. The

result is a database object that can be used (for most operations) like a dictionary. If you

create a new item, anydbm updates the database file.

>>> db['cleese.png'] = 'Photo of John Cleese.'

When you access one of the items, anydbm reads the file:

>>> print db['cleese.png']Photo of John Cleese.

If you make another assignment to an existing key, anydbm replaces the old value:

>>> db['cleese.png'] = 'Photo of John Cleese doing a silly walk.'>>> print db['cleese.png']Photo of John Cleese doing a silly walk.

Many dictionary methods, like keys and items, also work with database objects. So does

iteration with a for statement.

for key in db:print key

As with other files, you should close the database when you are done:

>>> db.close()