Berkeley DB and python


Berkeley DB
产品首页 , 官方下载地址

Berkeley DB XML
产品首页 , 官方下载地址

首先,我们可以通过一个简单的例子来说明如何使用bsddb:

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4. from bsddb import *
  5. demodb = hashopen('demo.db', 'c')
  6. for i in range(10):
  7.     demodb['%d'%i] = '%d'%(i*i)

我们通过一个简单的例子来说明,如何针对Berkeley DB XML来存储XML文档:

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4. from bsddb.db import *
  5. from dbxml import *
  6.  
  7. mgr = XmlManager()
  8. uc = mgr.createUpdateContext()
  9.  
  10. container = mgr.openContainer("demo.dbxml", DB_CREATE)
  11.  
  12. filename = 'demo'
  13. fileContents = """<?xml version="1.0" encoding="UTF-8"?>
  14. <result>OK</result>
  15. """
  16.  
  17. container.putDocument(filename, fileContents, uc)

在这个例子中,会创建一个名为demo.dbxml的数据库文件。

相应的,我们读取刚刚存储的内容,可以使用:

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4. from bsddb.db import *
  5. from dbxml import *
  6.  
  7. mgr = XmlManager()
  8.  
  9. container = mgr.openContainer("demo.dbxml")
  10. container.addAlias("demo")
  11.  
  12. qc = mgr.createQueryContext()
  13.  
  14. results = mgr.query("collection('demo')/result", qc)
  15.  
  16. for value in results:
  17.     document = value.asDocument()
  18.     print document.getName(), "=", value.asString()

参考书籍
《Getting Started with XQuery》Part1 , Part2

《Scaling Up with XQuery》Part1 , Part2

《Python 自省指南》


感谢您的关注。您现在可以 阅读留言(1)留下通告地址

One Response to “Berkeley DB and python



Leave a Reply

Note: Any comments are permitted only because the site owner is letting you post, and any comments will be removed for any reason at the absolute discretion of the site owner.

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image