Python中的简易数据库shelve

Python中为我们提供了一个简易的数据库。内存中的数据随着我们程序的闭关就结束了它的生命周期。那么怎么样把数据持久化到文件和数据库呢?

shelve模块简易数据库,下面来一个例子:

 1                                          
 2 import sys, shelve
 3 def store_person(db):#存储人的信息
 4     """
 5 
 6     Query user for data and store it in the shelf object
 7     """
 8     pid = raw_input('Enter unique ID number: ')#主键
 9     person = {}
10     person['name'] = raw_input('Enter name: ')
11     person['age'] = raw_input('Enter age: ')
12     person['phone'] = raw_input('Enter phone number: ')
13 
14     db[pid] = person
15 
16 def lookup_person(db):#查询人信息
17     """
18 
19     Query user for ID and desired field, and fetch the corresponding data from
20     the shelf object
21     """
22     pid = raw_input('Enter unique ID number: ')
23     temp = db[pid]
24     field = raw_input('Please enter name, age or phone')
25     field.strip().lower()
26     print field.capitalize() + ': ',temp[field]
27 
28 def enter_command():
29     cmd = raw_input('Enter command')
30     return cmd
31 
32 def main():
33     database = shelve.open('database')
34     try:
35         while True:
36             cmd = enter_command()
37             if cmd == 'store':
38                 store_person(database)
39             elif cmd == 'lookup':
40                 lookup_person(database)
41             elif cmd == 'quit':
42                 return
43     finally:
44         database.close()
45 
46 if __name__ == '__main__': main()

OK,这样你的数据不会随程序的结束而销毁了,不信自己把数据存进去,下次启动的时候再查查看,还会有的!

原文地址:https://www.cnblogs.com/hengli/p/2515386.html