python模块整理26-数据持久性pickle、shelve、SQLite

数据持久性

简单序列化
单纯滴保存数据到硬盘,而不保存数据之间的关系的过程称为“简单序列化”。
一、pickle
Python高级标准工具,处理一般对象存储(如pickle模块),处理文件中打包的二进制数据(如struct模块)
1、写入数据
pickle_dump(数据,文件)
>>> import pickle
>>> some_dict={'a':1,'b':2}
>>> pickle_file=open('/tmp/pypickle.data','w',0)
>>> pickle_dump(some_dict,pickle_file)
>>> pickle_file.close()
2、读取文件pickle.load(文件)
>>>pickle_file=open('/tmp/pypickle.data','r')
>>> pickle_file=open('/tmp/pypickle.data','r')
>>> get_data=pickle.load(pickle_file)
>>> get_data
{'a': 1, 'b': 2}
>>> pickle_file.close()
写入什么数据,读出来就什么数据
3、可自pickle自己创建的对象类型。
1)自定义pickle创建对象类型
# vim custom_class.py
#/usr/bin/env python
class MyClass():
def __init__(self):
self.data=[]
def __str__(self):
return "Custom Class MyClass Data:: %s" % str(self.data)
def add_item(self,item):
self.data.append(item)
2)调用自定义创建对象的类产生数据
# vim add_pickledata.py
#/usr/bin/env python
import pickle
import custom_class
my_obj=custom_class.MyClass()
my_obj.add_item(1)
my_obj.add_item(2)
my_obj.add_item(3)

pickle_file=open('/tmp/pickle.data','w')
pickle.dump(my_obj,pickle_file)
pickle_file.close()
# python add_pickledata.py #添加数据
3)读取前面产生的数据、
# vim read_pickledata.py
#/usr/bin/env python
import pickle
import custom_class
pickle_file=open('/tmp/pickle.data','r')
my_obj=pickle.load(pickle_file)
print my_obj
pickle_file.close()
# python read_pickledata.py
Custom Class MyClass Data:: [1, 2, 3]
4)pickle文件协议
协议是对文件如何进行格式化说明。
默认的协议几乎可读的格式,可以使用二进制格式
>>> pickle_file=open('/tmp/binpickle.data','wb')
>>> pickle_data={'a':1}
>>> pickle.dump(pickle_data,pickle_file,-1)
>>> pickle_file.close()
# cat /tmp/binpickle.data
?}qUaqKs.
open时'wb' 表示以二进制可写模式
dump时 -1 表示使用最高层的协议(二进制协议)
5)、cpickle
cpickle由C语言实现,建议使用2进制,使用语法和pickle相同

二、shelve
shelve存储中保存对象与简单地使用python字典相似
Shelve会自动把对象pickle生成按键读取的数据库,而此数据库导出类似于字典的接口.
1、写入数据
>>> import shelve
>>> dbase=shelve.open('/tmp/shelve.data')
>>> dbase
{}
>>> dbase['key']='some value' 写入
>>> dbase['name']='diege' 写入
>>> dbase.close()
dbase.sync 让数据立即从内存写入文件,防止文件没有close()时数据没有写入文件
>>> dbase=shelve.open('/tmp/shelve.data')
>>> dbase['level']=47
>>> dbase.sync
<bound method DbfilenameShelf.sync of {'name': 'diege', 'key': 'some value', 'level': 47}>
2、读取
>>> import shelve
>>> shtest=shelve.open('/tmp/shelve.data')
>>> shtest['key']
'some value'
>>> shtest['name']
'diege'
>>> shtest.close()

三、YAML
需要在Python应用与以另一种语言编写的应用之间获得数据,YAML是一个好的折中方案。
不是标准库需要安装
#easy_install PyYAML
写dump
读load
类似pickle
四、ZODB
和pickle和YAML类似,具体按需定义的功能。支持事务功能,提供更加可扩展的持久存储
不是标准库需要安装
easy_install ZODB3

关系序列化
一、SQLite
管理工具sqlitemanager,用法酷像phpmyadmin
1、创建数据
程序freebsd默认安装
数据保存在一个文件中,而不是分散到多个文件系统的多个目录中。
# sqlite3 inventory.db < inventory.sql
# ll
total 16
-rw-r--r-- 1 root wheel 13312 Mar 25 12:48 inventory.db
-rw-r--r-- 1 root wheel 1379 Mar 25 12:47 inventory.sql
2、使用
非标准库需要安装
# easy_install sqlite3
脚本使用 插入数据
import sqlite3
conn = sqlite3.connect('inventory.db') #建立连接对象
cursor = conn.execute("insert into inventory_operatingsystem (name,description) values ('Linux', '2.0.34 kernel');") #执行插入语句
cursor.fetchall() #查看返回值 #插入语句是没有返回值的
conn.commit() #提交
脚本使用 查询数据
import sqlite3
conn = sqlite3.connect('inventory.db') #建立连接对象
cursor = conn.execute('select * from inventory_operatingsystem;') #执行查询语句
cursor.fetchall() #查看返回值
[(1, u'Linux', u'2.0.34 kernel')]
1为主键,是数据库组自动设置为自增的。

更多参考 http://www.cnblogs.com/qq78292959/archive/2013/04/01/2993327.html

http://www.cnblogs.com/youxin/p/3546298.html

 

二、Storm ORM
ORM Object-Relational Mapping 对象关系映射
Strom是一个ORM
实例 插入数据
import storm.locals
import storm_model
import os
operating_system = storm_model.OperatingSystem()
operating_system.name = u'Windows'
operating_system.description = u'3.1.1'
db = storm.locals.create_database('sqlite:///%s' % os.path.join(os.getcwd(),
'inventory.db'))
store = storm.locals.Store(db)
store.add(operating_system)
store.commit()
实例 显示数据
import storm.locals
import storm_model
import os
db = storm.locals.create_database('sqlite:///%s' % os.path.join(os.getcwd(),
'inventory.db'))
store = storm.locals.Store(db)
for o in store.find(storm_model.OperatingSystem):
print o.id, o.name, o.description

posted on 2012-11-05 16:42  @Jin  阅读(2137)  评论(0编辑  收藏  举报

导航