Python USES Berkeley DB database instances

  • 2020-04-02 14:11:20
  • OfStack

This article is an example of python using Berkeley DB database.

The specific implementation method is as follows:


try: 
  from bsddb import db 
except ImportError: 
  from bsddb3 import db 
print db.DB_VERSION_STRING 
# Check if there is bsddb package  
 
def irecords(curs): 
  record = curs.first() 
  while record: 
    yield record 
    record = curs.next() 
     
adb = db.DB() 
adb.open('db_filename',dbtype = db.DB_HASH, flags = db.DB_CREATE) 
for i,w in enumerate('some word for example'.split()): 
  adb.put(w,str(i)) 
   
for key, data in irecords(adb.cursor()): 
  print key,data 
adb.close() 
print '*'*60 
# 
the_same_db = db.DB() 
the_same_db.open("db_filename") 
the_same_db.put('skidoo','23')# Join database  
the_same_db.put('for','change the data')# Change the data in the database  
for key, data in irecords(the_same_db.cursor()): 
  print key,data 
the_same_db.close()

The operation results are as follows:    


Berkeley DB 4.7.25: (May 15, 2008)
example 3
some 0
word 1
for 2
************************************************************
example 3
some 0
word 1
for change the data
skidoo 23

Here is a summary of the steps:

1. Initialize the database first


adb = db.DB()

2. Open the database


adb.open('db_filename',dbtype = db.DB_HASH, flags = db.DB_CREATE)

3. Insert or modify data in the database


adb.put('skidoo','23')# Join database 
adb.put('for','change the data')# Change the data in the database 

Close the database


adb.close()

I hope this article has helped you with your Python programming.


Related articles: