python berkeley DB操作——打开btree索引文件中的database

时间:2022-12-18 15:16:34

打开BDB中某个索引中的数据库代码:

from bsddb3 import db
import bsddb3 as bsddb
print db.DB_VERSION_STRING mydb = db.DB()
mydb.open('your_btree_db_filename', 'databsename', dbtype=db.DB_BTREE)
rec = cur.first()
while rec:
#print key value
print int(rec[0].encode('hex'), 16), "=>", len(rec[1])
rec = cur.next()
mydb.close()

注意:同一个db file中可能有多个database!

这样就和 /usr/local/BerkeleyDB.6.1/bin/db_dump your_btree_db_filename 结果一样了,dump结果如下所示:

VERSION=3
format=bytevalue
database=BLOCK_TIME_RANGE
type=btree
duplicates=1
db_pagesize=4096
HEADER=END
DATA=END
VERSION=3
format=bytevalue
database=xxxxyour databse name
type=btree
duplicates=1
db_pagesize=4096
HEADER=END
01000000 #=>key
5e096909f0fxxxxx # value
01000001 #=>key
5e096809f0ffff83xxxxxxx # value
xxxxxxxxxxxx more btree data xxxxxxxxxxxx

顺便补充,查看一个db中有多少数据库:

bdb = bsddb.btopen('32_20170228151803_qsb.idx', 'r')
print bdb.keys()
bdb.close()

再补充,打开reco DB示例:

from bsddb3 import db
import bsddb3 as bsddb
print db.DB_VERSION_STRING mydb = db.DB()
mydb.open('30_20170228145149_qsb.db',dbtype=db.DB_RECNO)
cur = mydb.cursor()
i = 0
f = open("data.bin", "wb")
rec = cur.first()
while rec:
#print rec
print rec[0], type(rec[1])
f.write(rec[1]) # write data to file
rec = cur.next()
i += 1
f.close()
mydb.close()