python 持久化存储
anydbm模块
1 import anydbm
2 db = anydbm.open("1_dbm", "c")
3 # Add an item.
4 db["www.python.org"] = "Python home page"
5 for i in range(100):
6 db[str(i)] = str(i)
7 #Keys and values must always be strings
8 # db["number"] = 1 # raise an error
9 print db["www.python.org"]
10 # Close and save to disk.
11 db.close()
12
13 import anydbm
14
15 db = anydbm.open("1_dbm", "r")
16
17 print db["www.python.org"]
18
19 # the size of 1_dbm.dat would not get small after delete some items
20 for i in range(50):
21 del db[str(i)]
22
23 print db["51"]
2 db = anydbm.open("1_dbm", "c")
3 # Add an item.
4 db["www.python.org"] = "Python home page"
5 for i in range(100):
6 db[str(i)] = str(i)
7 #Keys and values must always be strings
8 # db["number"] = 1 # raise an error
9 print db["www.python.org"]
10 # Close and save to disk.
11 db.close()
12
13 import anydbm
14
15 db = anydbm.open("1_dbm", "r")
16
17 print db["www.python.org"]
18
19 # the size of 1_dbm.dat would not get small after delete some items
20 for i in range(50):
21 del db[str(i)]
22
23 print db["51"]
marshal模块
View Code 1 # -*- coding: cp936 -*-
2 import marshal
3 """
4 1仅支持基本数据类型 dictionary, list, tuple, numbers, string
5 2不保证不用python版本之间的兼容
6 3帮助文档中指出dump函数的需要文件对象必须以二进制“wb”,“rb”的形式读写(不用b好像也行)
7 """
8 data = {12 : "twelve", "feep" : list("test"), 1.23 : 4 + 5j, (1, 2, 3) : u"unicode"}
9
10 f = open("2_ps_marshal.dat", "wb")
11
12 marshal.dump(data, f)
13 marshal.dump("a string type", f)
14
15 f.close()
16
17 #another file
18
19 import marshal
20
21 f = open("2_ps_marshal.dat", "r")
22
23 a = marshal.load(f)
24 b = marshal.load(f)
25
26 print a
27 print b
28
2
2 import marshal
3 """
4 1仅支持基本数据类型 dictionary, list, tuple, numbers, string
5 2不保证不用python版本之间的兼容
6 3帮助文档中指出dump函数的需要文件对象必须以二进制“wb”,“rb”的形式读写(不用b好像也行)
7 """
8 data = {12 : "twelve", "feep" : list("test"), 1.23 : 4 + 5j, (1, 2, 3) : u"unicode"}
9
10 f = open("2_ps_marshal.dat", "wb")
11
12 marshal.dump(data, f)
13 marshal.dump("a string type", f)
14
15 f.close()
16
17 #another file
18
19 import marshal
20
21 f = open("2_ps_marshal.dat", "r")
22
23 a = marshal.load(f)
24 b = marshal.load(f)
25
26 print a
27 print b
28
2
[c]pickle模块
View Code 1 import cPickle
2
3 data = {12 : "twelve", "feep" : list("test"), 1.23 : 4 + 5j, (1, 2, 3) : u"unicode"}
4
5
6 """dumps protocol/version 参数:
7 Protocol version 0 is the original ASCII protocol and is backwards compatible with earlier versions of Python.
8 Protocol version 1 is the old binary format which is also compatible with earlier versions of Python.
9 Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of new-style classes.
10 """
11
12 text = cPickle.dumps(data, 0)
13 print "protocal is 0", text
14
15 text = cPickle.dumps(data, 1)
16 print "protocal is 1", text
17
18 text = cPickle.dumps(data, 2)
19 print "protocal is 2", text
20
21 str = cPickle.loads(text)
22
23 print str
24
25
26 #another file
27 #use gzip module to compress the serialized file
28 #-*- coding:cp936 -*-
29
30 import cPickle, gzip
31
32 def save(filename, *objects):
33 """将对象存为压缩过的磁盘文件"""
34 f = gzip.open(filename, "wb")
35 [cPickle.dump(obj, f, protocol=2) for obj in objects]
36 f.close()
37
38 def load(filename):
39 """从压缩的磁盘文件中载入对象"""
40 f = gzip.open(filename, "rb")
41 while True:
42 try :
43 yield cPickle.load(f)
44 except EOFError:
45 break
46 f.close()
47
48 if __name__ == "__main__":
49 f = open("3_largeFile.txt", "rb")
50 save("3_compressed.dat", f.read())
51 gen = load("3_compressed.dat")
52 content = gen.next()
53 print content
54
55
2
3 data = {12 : "twelve", "feep" : list("test"), 1.23 : 4 + 5j, (1, 2, 3) : u"unicode"}
4
5
6 """dumps protocol/version 参数:
7 Protocol version 0 is the original ASCII protocol and is backwards compatible with earlier versions of Python.
8 Protocol version 1 is the old binary format which is also compatible with earlier versions of Python.
9 Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of new-style classes.
10 """
11
12 text = cPickle.dumps(data, 0)
13 print "protocal is 0", text
14
15 text = cPickle.dumps(data, 1)
16 print "protocal is 1", text
17
18 text = cPickle.dumps(data, 2)
19 print "protocal is 2", text
20
21 str = cPickle.loads(text)
22
23 print str
24
25
26 #another file
27 #use gzip module to compress the serialized file
28 #-*- coding:cp936 -*-
29
30 import cPickle, gzip
31
32 def save(filename, *objects):
33 """将对象存为压缩过的磁盘文件"""
34 f = gzip.open(filename, "wb")
35 [cPickle.dump(obj, f, protocol=2) for obj in objects]
36 f.close()
37
38 def load(filename):
39 """从压缩的磁盘文件中载入对象"""
40 f = gzip.open(filename, "rb")
41 while True:
42 try :
43 yield cPickle.load(f)
44 except EOFError:
45 break
46 f.close()
47
48 if __name__ == "__main__":
49 f = open("3_largeFile.txt", "rb")
50 save("3_compressed.dat", f.read())
51 gen = load("3_compressed.dat")
52 content = gen.next()
53 print content
54
55
shelve模块
1 import shelve
2
3 she = shelve.open("4_try.she", "c")
4
5 for c in "spam" :
6 she[c] = {c : 23}
7
8 print she
9
10 for c in she.keys():
11 print c, she[c]
12
13 she.close()
14
15
16 #another file
17 #how to modify the value
18 import shelve
19
20 she = shelve.open("4_try.she", "c")
21 #she = shelve.open("try.she", "c", writeback = True)
22
23 print she
24
25 print "original she[\"p\"] :", she["p"]
26
27 she["p"]["p"] = 99 # would not change the original she["p"] value
28 print "method one : ", she["p"]
29
30 a = she["p"] # one of the methods to change the original value
31 a["p"] = 99
32 she["p"] = a
33 print "method two : ", she["p"]
2
3 she = shelve.open("4_try.she", "c")
4
5 for c in "spam" :
6 she[c] = {c : 23}
7
8 print she
9
10 for c in she.keys():
11 print c, she[c]
12
13 she.close()
14
15
16 #another file
17 #how to modify the value
18 import shelve
19
20 she = shelve.open("4_try.she", "c")
21 #she = shelve.open("try.she", "c", writeback = True)
22
23 print she
24
25 print "original she[\"p\"] :", she["p"]
26
27 she["p"]["p"] = 99 # would not change the original she["p"] value
28 print "method one : ", she["p"]
29
30 a = she["p"] # one of the methods to change the original value
31 a["p"] = 99
32 she["p"] = a
33 print "method two : ", she["p"]
MySQLdb模块(选择合适的版本下载)
View Code 1 import MySQLdb
2 import pprint
3
4 con = MySQLdb.connect(host="127.0.0.1", port=3306, user="root", passwd="11", db="hellomysql")
5
6 cursor = con.cursor()
7
8 sql = "SELECT * FROM pet"
9
10 cursor.execute(sql)
11
12 pprint.pprint(cursor.description)
13
14 results = cursor.fetchall()
15
16 pprint.pprint(results)
17
18 print type(results)
19
20
2 import pprint
3
4 con = MySQLdb.connect(host="127.0.0.1", port=3306, user="root", passwd="11", db="hellomysql")
5
6 cursor = con.cursor()
7
8 sql = "SELECT * FROM pet"
9
10 cursor.execute(sql)
11
12 pprint.pprint(cursor.description)
13
14 results = cursor.fetchall()
15
16 pprint.pprint(results)
17
18 print type(results)
19
20
访问MySQL存储过程 (访问带传出参数的sp时,方法有点
,待改进)
View Code 1 import MySQLdb
2 import pprint
3
4 con = MySQLdb.connect(host="127.0.0.1", port=3306, user="root", passwd="11", db="hellomysql")
5
6 cursor = con.cursor()
7 cursor.nextset()
8 param2=list()
9 param3 = list()
10
11 t1 = cursor.callproc("Proc_test", ("snake", param2, param3))
12 cursor.execute("select @_Proc_test_1, @_Proc_test_2")
13
14 print param2
15
16 pprint.pprint(t1)
17
18
2 import pprint
3
4 con = MySQLdb.connect(host="127.0.0.1", port=3306, user="root", passwd="11", db="hellomysql")
5
6 cursor = con.cursor()
7 cursor.nextset()
8 param2=list()
9 param3 = list()
10
11 t1 = cursor.callproc("Proc_test", ("snake", param2, param3))
12 cursor.execute("select @_Proc_test_1, @_Proc_test_2")
13
14 print param2
15
16 pprint.pprint(t1)
17
18
访问SQL数据库(下载pyodbc)
#-*- coding:cp936 -*-
2 import pyodbc
3 import pprint
4
5
6 conn = pyodbc.connect("DSN=yourdsnname")
7 #the following sentence can work as well
8 #conn = pyodbc.connect("DRIVER={SQL Server};SERVER=servername;DATABASE=dbname;UID=sa;PWD=sa")
9
10 c = conn.cursor()
11
12 sql = "select * From AdTypeTree"
13
14 c.execute(sql)
15
16 rows = c.fetchall()
17
18 pprint.pprint(rows)
19 print rows[0][1]
2 import pyodbc
3 import pprint
4
5
6 conn = pyodbc.connect("DSN=yourdsnname")
7 #the following sentence can work as well
8 #conn = pyodbc.connect("DRIVER={SQL Server};SERVER=servername;DATABASE=dbname;UID=sa;PWD=sa")
9
10 c = conn.cursor()
11
12 sql = "select * From AdTypeTree"
13
14 c.execute(sql)
15
16 rows = c.fetchall()
17
18 pprint.pprint(rows)
19 print rows[0][1]
1 #-*- coding:cp936 -*-
2 import pyodbc
3 import pprint
4
5
6 conn = pyodbc.connect("DSN=yourdsnname")
7 #the following sentence can work as well
8 #conn = pyodbc.connect("DRIVER={SQL Server};SERVER=servername;DATABASE=dbname;UID=sa;PWD=sa")
9
10 c = conn.cursor()
11
12 sql = "select * From AdTypeTree"
13
14 c.execute(sql)
15
16 rows = c.fetchall()
17
18 pprint.pprint(rows)
19 print
2 import pyodbc
3 import pprint
4
5
6 conn = pyodbc.connect("DSN=yourdsnname")
7 #the following sentence can work as well
8 #conn = pyodbc.connect("DRIVER={SQL Server};SERVER=servername;DATABASE=dbname;UID=sa;PWD=sa")
9
10 c = conn.cursor()
11
12 sql = "select * From AdTypeTree"
13
14 c.execute(sql)
15
16 rows = c.fetchall()
17
18 pprint.pprint(rows)
19 print

浙公网安备 33010602011771号