The dbm module allows the creation, manipulation, and storage of simple key-value pairs in a database format. It provides a simple and efficient way to persistently store and retrieve data in a file, without having to use a full-fledged database management system.

The dbm module is used for backend storage by the shelve module which is commonly used for data persistence across executions.

To use the dbm module, we first need to import it in our program:

import dbm

print(dbm)

Basic Usage

The dbm.open() function is used to open a database for read or write operations. It has the following basic syntax:

dbm.open(filename, flag = 'r')

Where the filename is the name of the db file to be opened. The flag parameter controls how the database is opened, it defaults to 'r' meaning that a database is opened in read-only mode. All the four flags are shown in the following table:

r open an existing database with read-only access. An error is raised if a database with the given name is not found.
c open an existing database or create and open one. the opened database has both read and write access.
w Open an existing database with both read and write access. An error is raised if the database does not exist.
n Creates a new database every time. If a database with a similar name exists, it will be overwritten.

The data is always stored and accessed in binary format.

The opened database has a dictionary-like interface, this means that you can use dictionary methods like get(), keys(), values(), clear(), etc to perform various operations on the database.

Create and populate a new database

To create a new database, you can use the dbm.open() function with either the 'c' or 'n' flags. The 'c' flag only creates a new database if it does not already exist while 'n' always creates a new database, overwriting the existing one.

import dbm

db = dbm.open('cities.db', 'c')
db['Ottawa'] = 'Canada'
db['Tokyo'] = 'Japan'
db['Manilla'] = 'Phillipines'
db['Paris'] = 'France'
db['Berlin'] = 'Germany'
db.close()

In the above example, a file named cities.db will be created and populated with the data.

Reading from the database

You open and read from an existing database. Note that all the opening flags supports read operation. However, in cases where you know that you are only going to read and not write into the database, it is more efficient to use the 'r' flag.

Note that reading from the database always returns the data in binary format.

Read from cities.db

import dbm

db = dbm.open('cities.db', 'r')
print(db.keys())
print(db['Manilla'])
print(db['Tokyo'])
db.close()

[b'Tokyo', b'Manilla', b'Berlin', b'Nairobi', b'Asia', b'Europe', b'N.America', b'Africa', b'Ottawa', b'Paris']
b'Phillipines'
b'Japan' 

Error when performing database operations

Note that the database works like dictionaries as earlier mentioned. This means that you may get errors just like you would when using dictionaries. For example, if you use a key that does not exist in the database, a KeyError will be raised. 

import dbm

db = dbm.open('cities.db', 'r')
print(db['Delhi']) #with a non-exsiting key
db.close()

 File "C:\Python312\Lib\dbm\dumb.py", line 148, in __getitem__
    pos, siz = self._index[key]     # may raise KeyError
               ~~~~~~~~~~~^^^^^
KeyError: b'Delhi'

Lastly, the database keys must be strictly bytes or strings, using other objects as key will lead to errors. This is unlike in dictionary where you can use any immutable objects as a dictionary key.

import dbm

db = dbm.open('cities.db', 'w')
db[1] = 'Madrid' #raises an exception
db.close()

TypeError: keys must be bytes or strings