模拟数据库作业

作业思路:

1,用户选择相应的选项进行选择,1,注册,2登陆,....(增删改查)

2,使用装饰器实现登录认证

3,用户id只能增加,删除用户之后id便不再被使用.

4,查:查询遵循select 列名 where 条件/select * where 条件/select 列名 where phone like 133的模糊查询.

  4.1实现思路:1,首先让用户输入语法,首先进行判断语法是否正确(确定用户输入的包含了select和where关键字).2,判断列名是否存在name_list中,3,接下来就是切割用户输入的字符串,首先切割掉select,再切割where,得到用户输入的列名和条件,4,接下来操作文件循环文件,嵌套循环name_list再嵌套循环用户输入切割之后的列名列表.目的:最外层是为了最后输出文件内容,嵌套的里面两层是进行用户输入的列名与所有列名进行匹配.进而判断where后面的条件.(大体思路就这样了.手动省略号......)

5,修改操作,与查询开始的操作类似不在赘述,之后拿到用户要修改的内容之后,将原数据切割之后赋值给变量,此时的变量代表的就是old的数据列表,进而匹配到相应的修改数据位置,把新的数据修改掉即可,最后将修改之后的列表转化为逗号隔开的字符串写入文件完成操作

***需要改进的地方***

再目前的代码实现的仅仅只能判断用户一个条件.认为可以进行列名相同的修改操作达到判断多条件的功能.未完,待续......

# ! /usr/bin/env python3.6
# -*- coding: utf-8 -*-
# 2018/6/21 20:05

'''
文件存储格式如下:
id,name,age,phone,job
1,Alex,22,13651054608,IT
2,Egon,23,13304320533,Tearcher
3,nezha,25,1333235322,IT

现在需要对这个员工信息文件进行增删改查。
基础必做:
a.可以进行查询,支持三种语法:
select 列名1,列名2,… where 列名条件
支持:大于小于等于,还要支持模糊查找。
示例:
select name, age where age>22
select * where job=IT
select * where phone like 133
进阶选做:
b.可创建新员工记录,id要顺序增加c.可删除指定员工记录,直接输入员工id即可
d.修改员工信息
语法:set 列名=“新的值” where 条件
#先用where查找对应人的信息,再使用set来修改列名对应的值为“新的值”

注意:要想操作员工信息表,必须先登录,登陆认证需要用装饰器完成
其他需求尽量用函数实现'''
import os

li = ["注册", "登陆", '查询', '修改', '添加', '删除', '退出']
dic = {"name": None}
name_list = ['id', 'name', 'age', 'phone', 'job']
condition = ['>', '<', '=', 'like']


def register():
    user_name = input('请输入用户名>>>')
    passwd = input('请输入密码>>>')
    with open('user_info', 'r+', encoding='utf-8') as f:
        for item in f:
            if item.strip().split(',')[0] == user_name.strip():
                print('您输入的用户名已存在,请重新输入!')
                return
        else:
            f.write(user_name + ',' + passwd + '\n')
            print('注册成功!!!')


def wrapper(func):
    def inner(*args, **kwargs):
        if dic['name'] is None:
            print("请先登录!!!")
            return
        ret = func(*args, **kwargs)
        return ret

    return inner


def first_menu():
    '''选择菜单'''
    for num, item in enumerate(li):
        print(num + 1, item, end=' ')


def loggin():
    print("欢迎登陆")
    flag = True
    while flag:
        username = input("请输入您的用户名>>>").strip()
        passwd = input("请输入您的密码>>>").strip()
        with open('user_info', encoding='utf-8') as f:
            for item in f.readlines():
                name, pwd = item.strip().split(",")
                if name == username and passwd == pwd:
                    dic['name'] = username
                    print('登陆成功!!!')
                    flag = False
                    break
            else:
                print('用户名密码输入错误')


@wrapper
def add_info():
    print("增加员工信息")
    flag1 = True
    while flag1:
        user_input = input("请输入员工信息(姓名,年龄,电话,工作)>>>").strip()
        user_input = user_input.replace("", ',')
        with open("a.txt", 'r+', encoding='utf-8') as f:
            for item in f.readlines():
                if item.strip().split(',')[1] == user_input.split(',')[0]:
                    print('您输入的用户信息已存在')
                    return
            else:
                with open("count_id", encoding='utf-8') as f1, open('count_id1', 'w', encoding='utf-8') as f2:
                    count = f1.read()
                    count = count.strip().split("=")[-1]
                    f.write(count + ',' + user_input + '\n')
                    f2.write("count=" + str(int(count) + 1))
                os.remove('count_id')
                os.rename('count_id1', 'count_id')


@wrapper
def reduce_info():
    print("删除员工信息")
    flag = True
    user_choice_id = input("请选择你要删除的员工id>>>")
    if user_choice_id.isdigit():
        with open('a.txt', 'r', encoding='utf-8') as f, open('a1.txt', 'w', encoding='utf-8') as ff:
            for item in f:
                if item.strip().split(",")[0] == user_choice_id:
                    flag = False
                    print('删除成功!!!')
                    continue
                else:
                    ff.write(item)
            else:
                while flag:
                    print("没有您要删除的员工信息")
                    break
        os.remove('a.txt')
        os.rename('a1.txt', 'a.txt')
    else:
        print('请输入正确的员工id')


@wrapper
def select_info():
    flag = False
    # with open('a.txt', encoding='utf-8') as f:
    #     for item in f.readlines():
    #         print(item.strip())
    # print("查找员工信息")
    user_choice = input('请输入查找暗号>>>').strip()  # select name, age where age>22   /   select * where age>22
    if 'select' in user_choice and 'where' in user_choice:
        lst = user_choice.split("select")[1:]  # [' name, age where age>22']    /
        lst1 = lst[0].split("where")  # [' name, age ', ' age>22']  lst1[1].strip() = 'age>22'    /   [' *', ' age>22']
        lst_info = lst1[0].split(",")  # [' name', ' age ']    /   [' *']
        for item in lst_info:
            if lst_info[0].strip() == "*":
                lst_info = name_list
                break
            elif item.strip() not in name_list:
                print("您输入含有不存在列名,请重新选择")
                return
        '''这里已经确定输入的内容合法,下面打开文件进行查询'''
        with open('a.txt', 'r', encoding='utf-8') as f:
            for name in f:  # 循环文件
                if name.strip().split(',')[0] == 'id':
                    for name in lst_info:
                        print(name.strip(), end='       ')
                    print()
                    continue
                for item in name_list:  # item = 'name' name_list = ['id', 'name', 'age', 'phone', 'job']
                    for el in lst_info:  # [' name', ' age '] 或者只有一个['*']
                        if item == el.strip():
                            for judje in condition:
                                if judje in lst1[1].strip():
                                    if condition.index(judje) == 0:  # 确定是age大于操作
                                        if int(name.strip().split(",")[
                                                   name_list.index(lst1[1].strip().split(judje)[0])]) > int(
                                                lst1[1].strip().split(judje)[-1]):
                                            print(name.strip().split(',')[name_list.index(el.strip())], end='       ')
                                            flag = True
                                    elif condition.index(judje) == 1:
                                        '''小于号操作'''
                                        if int(name.strip().split(",")[
                                                   name_list.index(lst1[1].strip().split(judje)[0])]) < int(
                                                lst1[1].strip().split(judje)[-1]):
                                            print(name.strip().split(',')[name_list.index(el.strip())], end='       ')
                                            flag = True
                                    elif condition.index(judje) == 2:
                                        '''等于号操作,这里两种情况,1,id和age的大小。2,job的匹配'''
                                        if lst1[1].strip().split('=')[0] == 'job':  # 'job = it'
                                            if name.strip().split(',')[
                                                name_list.index(lst1[1].strip().split(judje)[0])].lower() == \
                                                    lst1[1].strip().split(judje)[-1].lower():
                                                print(name.strip().split(',')[name_list.index(el.strip())],
                                                      end='       ')
                                                flag = True
                                        elif int(name.strip().split(",")[
                                                     name_list.index(lst1[1].strip().split(judje)[0])]) == int(
                                                lst1[1].strip().split(judje)[-1]):
                                            print(name.strip().split(',')[name_list.index(el.strip())], end='       ')
                                            flag = True
                                    elif 'like' in lst1[1].strip():  # lst1[1].strip() = 'phone like 133'
                                        '''模糊查询'''
                                        lst_phone = lst1[1].strip().split(
                                            'like')  # lst_phone = ['phone ', ' 133'] 注意:去空格
                                        # print(lst_phone)
                                        if lst_phone[1].strip() in name.strip().split(',')[
                                            name_list.index(lst_phone[0].strip())]:
                                            print(name.strip().split(',')[name_list.index(el.strip())], end='       ')
                                            flag = True
                while flag:
                    print()
                    flag = False
    else:
        print('暗号语法错误,请重新选择')


#     select name, age where age>22
#     select * where job=IT
#     select * where phone like 133
@wrapper
def modify_info():
    '''修改之前要先进行查找,根据语法条件,删选出列名,新的值,where后面是旧的值'''
    print("修改信息")
    flag = True
    # set 列名 =“新的值” where  条件
    user_modify = input("请输入修改的暗号>>>").strip()  # set name = 超人 where name = 陈润
    if 'set' in user_modify and 'where' in user_modify:
        lst_user1 = user_modify.split('set')[1:][0].split('where')  # lst_user1 = ['name = 超人 ', ' name = 陈润']
        old_value = lst_user1[1].strip()  # 'name = 陈润'
        new_value = lst_user1[0].strip()  # 'name = 超人'
        with open('a.txt', 'r', encoding='utf-8') as f, open('a1.txt', 'w', encoding='utf-8') as ff:
            # ff.write('id,name,age,phone,job\n')
            for item in f:
                if item.strip().split(',')[name_list.index(old_value.split('=')[0].strip())] == old_value.split('=')[
                    1].strip():
                    lst = item.strip().split(',')  # [4,陈润,23,17610780919,it]
                    lst[name_list.index(old_value.split('=')[0].strip())] = new_value.split('=')[1].strip()
                    s = ','.join(lst)
                    ff.write(s + '\n')
                    print("修改成功!!!")
                    flag = False
                else:
                    ff.write(item)
            else:
                while flag:
                    print('请输入正确的信息')
                    break
        os.remove('a.txt')
        os.rename('a1.txt', 'a.txt')
    else:
        print('您输入的暗号有误')


def main():
    while True:
        first_menu()
        user_input = input("请输入您的选择>>>").strip()
        if user_input == "1":
            register()
        elif user_input == "2":
            loggin()
        elif user_input == '3':
            select_info()
        elif user_input == '4':
            modify_info()
        elif user_input == '5':
            add_info()
        elif user_input == '6':
            reduce_info()
        elif user_input == '7':
            break
        else:
            print('请输入正确的序号')


if __name__ == '__main__':
    main()
View Code

笔者水平有限,如有需要修改的地方,还望朋友指出,鄙人不胜感激!!!

扫描二维码关注公众号,回复: 1716178 查看本文章

猜你喜欢

转载自www.cnblogs.com/chenrun/p/9216479.html