1. 程式人生 > >python-作業:員工信息表

python-作業:員工信息表

輸入 .get lin del 打包 staf com 字典 獲取

程序可實現以下功能:
1、查詢,輸入select name,age from staff_table where age > 22,查詢到符合要求的信息;
輸入select * from staff_table where dept = "IT",查詢到符合要求的信息;
輸入select * from staff_table where enroll_date like "2013",查詢到符合要求的信息。
2、創建,輸入insert Mickle,22,13651054608,IT,2013-04-01,加信息加入的員工信息表中。
3、刪除,輸入delect id,將指定的id號員工信息刪除。
4、修改,輸入update staff_table set dept = "Market" where dept = "IT",將要修改的內容修改。

程序還提供help功能,為用戶輸入正確的sql語句格式提供幫助。

技術分享

import os           #導入os模塊,方便文件的刪除和改名

def info_display():      #打印程序啟動信息
    print("-".center(60, "-"))
    print("歡迎來到員工管理系統".center(50," "))
    print("【輸入help顯示幫助信息】".center(50, " "))
    print("-".center(60, "-"))
    sql = input("請輸入\033[1;31msql\033[0m信息>>>>").strip("")
    if sql == "q" or sql == "quit":                #用戶如果輸入q,程序退出
        exit(" Bye Bye ".center(60, "-"))
    elif sql == "help":                            #用戶輸入help,打印help信息,help信息為打印的格式
        print("\033[1;35m 查詢 輸入格式:\n\tselect name,age from staff_table where age > 22\033[0m")
        print("\033[1;35m 創建 輸入格式:\n\tinsert Mickle,22,13651054608,IT,2013-04-01\033[0m")
        print("\033[1;35m 修改 輸入格式:\n\tupdate staff_table set dept = \"Market\" where dept = \"IT\"\033[0m")
        print("\033[1;35m 刪除 輸入格式:\n\tdelete 5\033[0m")
    else:
        sql_parse(sql)                              #用戶輸入正確的sql語法,調用sql解析函數

def sql_parse(sql):                                #對用戶輸入的sql語句進行解析,根據sql語句調用不同的函數
    func_choice = {"insert": insert, "delete": delete, "update": update, "select": select}
    sql_list = sql.replace(",", " ").split()  # 將sql解析成列表形式
    if sql_list[0] == "select":                   #如果用戶輸入的sql語句是查詢
        sql_dict = {"from": [], "where": [], "limit": []}
        tag = False
        for item in sql_list:                        #根據sql解析出sql_dict
            if tag and item in sql_dict:
                tag = False
            if not tag and item in sql_dict:
                tag = True
                key = item
                continue
            if tag:
                sql_dict[key].append(item.strip(‘\"‘))
        func_choice.get(sql_list[0])(sql_dict)                  #解析出sql_dict後,傳入查詢函數,並調用查詢函數
    elif sql_list[0] == "insert":                        #如果用戶輸入的sql語句是創建
        sql_dict = {}
        sql_list.remove("insert")
        sql_dict.setdefault("values",sql_list)                 #解析出sql_dict,傳入創建函數
        insert(sql_dict)                                           #調用創建函數
    elif sql_list[0] == "delete":                               #解析出sql_dict後,傳入刪除函數,並調用查詢函數
        delete_id = int(sql_list[1])                                #獲取用戶要刪除的id
        delete(delete_id)                                       #調用刪除函數
    elif sql_list[0] == "update":                                 #如果用戶輸入的sql語句是修改
        sql_dict = {"set":[],"where":[],"update":[]}
        tag = False
        for items in sql_list:                                #根據用戶的sql,解析出sql_dict字典
            if tag and items in sql_dict:
                tag = False
            if not tag and items in sql_dict:
                tag = True
                key = items
                continue
            if tag:
                sql_dict[key].append(items.strip(‘\"‘))
        update(sql_dict)                                 #傳入修改函數,並調用修改函數
    return sql_list

def insert(sql_dict):                                     #創建信息函數
    with open("staff_table","ab+") as f:
        offs = -100
        while True:
            f.seek(offs,2)
            lines = f.readlines()
            if len(lines) > 1:
                last = lines[-1]
                break
            offs *= 2
        last = last.decode(encoding="utf-8")
        last_id = int(last.split(",")[0])
        new_id = last_id + 1
        record = sql_dict.get("values")
        record.insert(0,str(new_id))
        record_str = ",".join(record)+"\n"
        f.write(bytes(record_str,encoding="utf-8"))
        f.flush()
        print("\033[1;31m創建成功 \033[0m")

def delete(delete_id):                               #刪除函數
    with open("staff_table","r",encoding="utf-8") as f1,open("staff_table_bak","w",encoding=‘utf-8‘) as f2:
        del_count = 1
        for line in f1:
            if del_count != delete_id:
                f2.write(line)
            elif del_count == delete_id:
                pass
            del_count += 1
    print("\033[1;31m刪除成功 \033[0m")
    os.remove("staff_table")                      #刪除原員工信息文件
    os.rename("staff_table_bak","staff_table")              #修改新員工信息文件名

def update(sql_dict):                             #修改函數
    set_list = sql_dict.get("set")                   #獲取要修改的內容
    set_key = set_list[0]
    where_list = sql_dict.get("where")               #獲取要修改的文件內容
    with open("staff_table", "r", encoding="utf-8") as f1, open("staff_table_bak", "w", encoding=‘utf-8‘) as f2:
        for line in f1:
            title = "id,name,age,phone,dept,enroll_date"
            dic = dict(zip(title.split(","),line.split(",")))          #將文件每一行打包成字典的形式
            if logic_action(dic,where_list):                           # 邏輯判斷,調用邏輯判斷函數
                line = line.replace(dic[set_key],set_list[2])           #修改需要修改的那一行內容
            f2.write(line)                                              #將原文件寫進新文件
    print("\033[1;31m修改成功 \033[0m")
    os.remove("staff_table")
    os.rename("staff_table_bak", "staff_table")

def select(sql_dict):                                         #查詢函數
    title = "id,name,age,phone,dept,enroll_date"
    f = open("staff_table", "r", encoding="utf-8")    # 1、找到數據庫
    res = []
    for line in f:
        dict1 = dict(zip(title.split(","), line.strip().split(",")))
        where_list = sql_dict.get("where")
        if len(where_list) != 0:
            if logic_action(dict1, where_list):  # 邏輯判斷,調用邏輯判斷函數
                res.append(line.strip())
        else:
            res = f.readlines()
    print("查詢到的信息有 \033[1;35m %s \033[0m 條"%len(res))
    for i in res:
        print("分別是\033[1;35m [%s]\033[0m "%i)
    return res

def logic_action(dict1, where_list):       #邏輯判斷函數,如果文件的信息符合要求,就返回True
    tag = False
    if where_list[1] == "<":
        if dict1[where_list[0]] < where_list[2]:
            tag = True
    elif where_list[1] == "=":
        if dict1[where_list[0]] == where_list[2]:
            tag = True
        else:pass
    elif where_list[1] == ">":
        if dict1[where_list[0]] > where_list[2]:
            tag = True
        else:pass
    elif where_list[1] == "like":
            if where_list[2] in dict1[where_list[0]]:
                tag = True
    return tag

while True:
    try:
        info_display()
    except IndexError as e:
        print("【%s】,請輸入正確的格式"%e)              #如果用戶輸入的格式不正確,就打印提示

  

python-作業:員工信息表