0

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 Unfun Cat
  • 29,987
  • 31
  • 114
  • 156

2 Answers2

1

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 
cyberj0g
  • 3,707
  • 1
  • 19
  • 34
The Unfun Cat
  • 29,987
  • 31
  • 114
  • 156
  • Be careful, bytes(n) where n is integer creates byte array of length n, it doesn't convert n to bytes! Edited your answer. – cyberj0g Dec 17 '15 at 20:19
1

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.

amirouche
  • 7,682
  • 6
  • 40
  • 94