您的位置:首页 > 编程语言 > Python开发

Python利用shelve模块设计简单数据库程序

2017-09-06 23:40 351 查看
欢迎访问我的网站omegaxyz.com

利用shelve模块写数据库文件在程序关闭时仍然能存储之前的数据。

将所有内容都放到函数中会让程序更加结构化。

主程序放在main函数中,只有在if__name__==’main’条件成立的时候才被调用

意味着可以在其他程序中将这个程序作为模块导入,然后调用main函数。

我在main函数中打开数据库(shelf),然后将其作为参数传给另外需要它的函数。

我也可以使用全局变量,毕竟这个程序很小。不过,在大多数情况下最好避免用全局变

量,除非有充足的理由要使用它。

我使用try/finally确保数据库能够正确关闭。()我们永远不知道什么时候会出错程序会抛出异常)。如果程序在没有正确关闭数据库的情况下终止,那么,数据库文件可能被损坏了,这样的数据文件是毫无用处的。

下面是整个数据库文件代码:

#©OmegaXYZ
import shelve

def store_person(db):
"Query user for data and store it in the shelf object"

pid = input("Enter unique ID number: ")
person = {}
person['name'] = input("input your name: ")
person['age'] = input("input your age: ")
person['phone'] = input("Enter your phone number: ")

db[pid] = person

def lookup_person(db):
"Query user for ID and desired field. and fetch the corresponding data from the shelf object"

pid = input("Enter ID number")
field = input("What would you like to know?  (name, age, phone)")
field = field.strip().lower()
print(field.capitalize() + ':' + db[pid][field])

def print_help():
print("The available commands are: ")
print("store : Stores information about a person")
print("lookup : Look up a person from ID number")
print("quit :
4000
Save changes and exit")
print("? : Print this message")

def enter_command():
cmd = input("Enter command (? for help): ")
cmd = cmd.strip().lower()
return cmd

def main():
database = shelve.open('E:\\Temporary\\database.dat')# You may want to change this name
try:
while True:
cmd = enter_command()
if cmd == 'store':
store_person(database)
elif cmd == 'lookup':
lookup_person(database)
elif cmd == '?':
print_help()
elif cmd == 'quit':
return
finally:
database.close()

if __name__ == '__main__':main()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: