Question

I'm using python 2.7.3 and and Berkeley DB to store data. I didn't find much information about that module, only in python docks. I saw there some function described, but I didn't see instruction on how to delete a record from database. Help please, if you know how to delete a record and is that possible using bsddb ?

Was it helpful?

Solution

According to the documentation:

Once instantiated, hash, btree and record objects support the same methods as dictionaries.

So, you can use del db_object['key'] to delete specific record like a dictionary.

>>> import bsddb
>>> db = bsddb.hashopen('a.db', 'c')
>>> db['a'] = '1'
>>> db.keys()
['a']
>>> del db['a'] # <-----
>>> db.keys()
[]

db_object.pop('key') also works.

>>> db['b'] = '2'
>>> db.keys()
['b']
>>> db.pop('b')
'2'

del, .pop() with non-existing key will raise KeyError or similar exception. If you want ignore non-existing key, use .pop('key', None):

>>> db.pop('b') # This raises an exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/_abcoll.py", line 497, in pop
    value = self[key]
  File "/usr/lib/python2.7/bsddb/__init__.py", line 270, in __getitem__
    return _DeadlockWrap(lambda: self.db[key])  # self.db[key]
  File "/usr/lib/python2.7/bsddb/dbutils.py", line 68, in DeadlockWrap
    return function(*_args, **_kwargs)
  File "/usr/lib/python2.7/bsddb/__init__.py", line 270, in <lambda>
    return _DeadlockWrap(lambda: self.db[key])  # self.db[key]
KeyError: 'b'
>>> db.pop('b', None) # This does not.
>>>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top