- ZODB虽然是OODB, 但是任何有一些和关系数据库类似的概念
ZODB的数据存储形式, 是多选的, 可以是普通文件(FileStorage), DB4和ZEO连接.
- Python类通过继承Persistent可以变为ZODB化的.
- ZODB是基于"事务"的.
例子
- 先来看一个例子, 这个例子是可以运行的, 源于《ZODB/ZEO Programming Guide》
1 from ZODB import FileStorage, DB
2 import ZODB
3 from Persistence import Persistent
4 from BTrees.OOBTree import OOBTree
5
6 class User(Persistent):
7 pass
8
9 def test1():
10 storage = FileStorage.FileStorage("test-filestorage.fs")
11 db = DB(storage)
12 conn = db.open()
13 dbroot = conn.root()
14 # Ensure that a 'userdb' key is present
15 # in the root
16 if not dbroot.has_key('userdb'):
17 dbroot['userdb'] = OOBTree()
18 userdb = dbroot['userdb']
19 # Create new User instance
20 newuser = User()
21 # Add whatever attributes you want to track
22 newuser.id = 'amk'
23 newuser.first_name = 'Andrew'
24 newuser.last_name = 'Kuchling'
25 # Add object to the BTree, keyed on the ID
26 userdb[newuser.id] = newuser
27 # Commit the change
28 get_transaction().commit()
29 conn.close()
30 storage.close()
31
32 def test2():
33 storage = FileStorage.FileStorage("test-filestorage.fs")
34 db = DB(storage)
35 conn = db.open()
36 dbroot = conn.root()
37 it = [dbroot]
38 for t in it:
39 for k, v in t.items():
40 if isinstance(v, OOBTree):
41 print k, ':'
42 it.append(v)
43 elif isinstance(v, User):
44 print 'Key:', k
45 print 'ID:', v.id
46 print 'first_name:', v.first_name
47 print 'last_name:', v.last_name
48
49 if __name__ == "__main__":
50 test1()
51 test2()
- test1向数据库写数据, test2从数据库读数据.