문제

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

도움이 되었습니까?

해결책

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 

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top