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

欢迎访问我的网站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 : 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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值