python实现数据库增删改查
Posted 飞蝎儿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python实现数据库增删改查相关的知识,希望对你有一定的参考价值。
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实现数据库增删改查的主要内容,如果未能解决你的问题,请参考以下文章