Question

I am trying to create a BerkeleyDB using the hash access method, like so:

>>> from bsddb3 import db
>>> dben = DB()
>>> dben.open("filename", None, db.DB_HASH, db.DB_CREATE)

However, when I try to insert an entry, nothing works:

>>> dben.put(3,2)

results in

Traceback (most recent call last): File "", line 1, in dben.put(3,2) TypeError: Integer keys only allowed for Recno and Queue DB's

Attempting

>>> dben[2] = 1

it gives the same error.

How do I add an entry to my hash BerkeleyDB?

Using cntrl-space for autocomplete I can see no relevant methods. The same goes for the docs: PyBSDDB v5.3.0 documentation

Was it helpful?

Solution

The only (ugly) workaround on Python 3+ is to encode string to bytes first:

dben.put(bytes(str(3), "ascii"), bytes(str(2), "ascii"))

or, more conveniently:

dben.put(str(3).encode("ascii"), str(2).encode("ascii"))

>>> dben.exists(bytes(2, "ascii"))
False
>>> dben.exists(bytes(3, "ascii"))
True 

OTHER TIPS

bsddb stores as key and value only bytes. So you have to convert your value to bytes first. The prefered method is to use the struct python module.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top