对于面向对象数据库,对象关系数据库, 对象数据库,大家可能非常疑惑, 我也不能完全明白, 最大的原因是现在这方面的理论支持和标准还不是很完善。我对对象数据库理解是用来保存类实例的数据库, 是数据持久化的解决方案。
ZODB 是Z Object Database. 是python用于数据持久化的模块。
pip install ZODB
本地文件保存类实例
测试类
from persistent import Persistent
class Host(Persistent):
user = None
password = None
times = 1
def __init__(self, user, password, times):
self.user = user
self.password =password
self.times = times
def run(self):
print('user: {}'.format(self.user))
print('password: {}'.format(self.password))
for i in range(1, self.times + 1):
print('hello command {}'.format(i))
写类实例
import transaction
from ZODB import FileStorage, DB
storage = FileStorage.FileStorage('rock.db')
db = DB(storage)
connection = db.open()
root = connection.root()
root['rock'] = Host('rock', '123456', 2)
root['sandy'] = Host('sandy', '654321', 3)
transaction.commit()
connection.close()
db.close()
storage.close()
读类实例并执行方法
from ZODB import FileStorage, DB
storage = FileStorage.FileStorage('rock.db')
db = DB(storage)
connection = db.open()
root = connection.root()
root['rock'].run()
connection.close()
db.close()
storage.close()
output:
user: rock
password: 123456
hello command 1
hello command 2
远端数据库ZEO保存类实例
ZEO: Zope Enterprise Objects
pip install ZEO
搭建ZEO Server
- 命令行:
runzeo -a 0.0.0.0:52200 -f rock.db
- 配置文件
<zeo>
address 0.0.0.0:52200
</zeo>
<filestorage>
path /root/rock.db
</filestorage>
<eventlog>
<logfile>
path /root/zeo.log
format %(asctime)s %(message)s
</logfile>
</eventlog>runzeo --configure zeo.xml
写类实例
import transaction
from ZODB import FileStorage, DB
from ZEO import ClientStorage
storage = ClientStorage.ClientStorage(('10.207.69.19', 52200))
db = DB(storage)
connection = db.open()
root = connection.root()
root['rock'] = Host('rock', '123456', 1)
root['sandy'] = Host('sandy', '654321', 2)
transaction.commit()
connection.close()
db.close()
storage.close()
读类实例并执行方法
import transaction
from ZODB import FileStorage, DB
from ZEO import ClientStorage
storage = ClientStorage.ClientStorage(('10.207.69.19', 52200))
db = DB(storage)
connection = db.open()
root = connection.root()
root['rock'].run()
transaction.commit()
connection.close()
db.close()
storage.close()
output:
user: rock
password: 123456
hello command 1
对比关系型数据库,这个是不是很帅气!