码迷,mamicode.com
首页 > 数据库 > 详细

python实现数据库增删改查

时间:2019-02-15 17:30:59      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:用户输入   column   lin   student   for   list   ret   sele   turn   

column_dic = {"id": 0, "name": 1, "age": 2, "phone": 3, "job": 4}


def get_show_list(col_condition): # "select age,name"
    """
    获取要展示的列名
    :param col_condition: 用户输入的select条件
    :return: 列名组成的列表
    """
    col_info_list = col_condition.strip().split("select")  # ["", "age,name"]
    col_info_list = [col_info_item for col_info_item in col_info_list if col_info_item.strip()]  # ["age,name"]
    if col_info_list:
        col_info = col_info_list[0].strip()  # "age,name"
        if "*" in col_info:
            return column_dic.keys()
        elif col_info:
            ret = col_info.split(",")  # [" age ","name"]
            return [item.strip() for item in ret]  # ["age","name"]
        else:
            print(col_info)


def filter_handler(operate, con):  # ">" , "age>22"
    selected_list = []
    col, val = con.split(operate)
    col = col.strip()
    val = val.strip()
    judge = "int(line_list[column_dic[col]]) %s int(val)" % operate if operate == "<" or operate == ">"         else "line_list[column_dic[col]] %s val" % operate
    f = open("student", encoding="utf-8")
    for line in f:
        line_list = line.strip().split(",")
        if eval(judge):
            selected_list.append(line_list)
    f.close()
    return selected_list


def get_selected_line(con):  # con = "age>22"
    """
    获取要查找的行,并将每一行作为列表项存储到selected_list
    :param con:
    :return:
    """
    if ">" in con:
        selected_list = filter_handler(">", con)
    elif "<" in con:
        selected_list = filter_handler("<", con)
    elif "=" in con:
        selected_list = filter_handler("==", con.replace("=", ‘==‘))
    elif "like" in con:
        selected_list = filter_handler("in", con)
    return selected_list


def show(selected_list, show_list):
    for selected_item in selected_list:
        for col in show_list:
            print(selected_item[column_dic[col]], end=" ")
        print()


condition = input(">>>")  # "select age,name where age>22"
ret = condition.split(‘where‘)  # ["select age,name", "age>22"]
con = ret[1].strip()  # "age>22"
show_list = get_show_list(ret[0])  # ["name", "age"]
selected_list = get_selected_line(con)
show(selected_list, show_list)

  

python实现数据库增删改查

标签:用户输入   column   lin   student   for   list   ret   sele   turn   

原文地址:https://www.cnblogs.com/nxrs/p/10384558.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!