Python编程 模拟SQL语句 实现对员工信息的增删改查

简介: 使用python实现员工系统并且具有员工信息增删改查等基础功能

一、问题描述


用 Python 模拟 sql 语句,实现对员工信息的增删改查。


  • 封装函数,传入参数:文件路径和 sql 命令。
  • 模拟 sql 语句实现对员工信息的现增删改查,并打印结果。


二、Python编程


导入需要的依赖库


# -*- coding: UTF-8 -*-"""@Author   :叶庭云@file     :实训第二次作业@function :封装函数  根据输入的文件路径和sql命令            模拟sql语句实现对员工信息的现增删改查"""importreimportos


函数式编程


defsql_parse(sql_, key_list):
"""    解析sql命令字符串,按照key_lis列表里的元素分割sql得到字典形式的命令sql_dic    :param sql_:    :param key_list:    :return:    """sql_list= []
sql_dic= {}
foriinkey_list:
b= [j.strip() forjinsql_.split(i)]
iflen(b) >1:
iflen(sql_.split('limit')) >1:
sql_dic['limit'] =sql_.split('limit')[-1]
ifi=='where'ori=='values':
sql_dic[i] =b[-1]
ifsql_list:
sql_dic[sql_list[-1]] =b[0]
sql_list.append(i)
sql_=b[-1]
else:
sql_=b[0]
ifsql_dic.get('select'):
ifnotsql_dic.get('from') andnotsql_dic.get('where'):
sql_dic['from'] =b[-1]
ifsql_dic.get('select'):
sql_dic['select'] =sql_dic.get('select').split(',')
ifsql_dic.get('where'):
sql_dic['where'] =where_parse(sql_dic.get('where'))
returnsql_dicdefwhere_parse(where):
"""    格式化where字符串为列表where_list,用'and', 'or', 'not'分割字符串    :param where:    :return:    """casual_l= [where]
logic_key= ['and', 'or', 'not']
forjinlogic_key:
foriincasual_l:
ifinotinlogic_key:
iflen(i.split(j)) >1:
ele=i.split(j)
index=casual_l.index(i)
casual_l.pop(index)
casual_l.insert(index, ele[0])
casual_l.insert(index+1, j)
casual_l.insert(index+2, ele[1])
casual_l= [kforkincasual_lifk]
where_list=three_parse(casual_l, logic_key)
returnwhere_listdefthree_parse(casual_l, logic_key):
"""    处理临时列表casual_l中具体的条件,'staff_id>5'-->['staff_id','>','5']    :param casual_l:    :param logic_key:    :return:    """where_list= []
foriincasual_l:
ifinotinlogic_key:
b=i.split('like')
iflen(b) >1:
b.insert(1, 'like')
where_list.append(b)
else:
key= ['<', '=', '>']
new_lis= []
opt=''lis= [jforjinre.split('([=<>])', i) ifj]
forkinlis:
ifkinkey:
opt+=kelse:
new_lis.append(k)
new_lis.insert(1, opt)
where_list.append(new_lis)
else:
where_list.append(i)
returnwhere_listdefsql_action(sql_dic, titles):
"""    把解析好的sql_dic分发给相应函数执行处理    :param sql_dic:    :param titles:    :return:    """key= {'select': select,
'insert': insert,
'delete': delete,
'update': update}
res= []
foriinsql_dic:
ifiinkey:
res=key[i](sql_dic, titles)
returnresdefselect(sql_dic, title_):
"""    处理select语句命令    :param sql_dic:    :param title_:    :return:    """withopen(data_path, 'r', encoding='utf-8') asfh:
filter_res=where_action(fh, sql_dic.get('where'), title_)
limit_res=limit_action(filter_res, sql_dic.get('limit'))
search_res=search_action(limit_res, sql_dic.get('select'), title_)
returnsearch_resdefinsert(sql_dic):
"""    处理insert语句命令    :param sql_dic:    :return:    """withopen(data_path, 'r+', encoding='utf-8') asfp:
data_=fp.readlines()
phone_list= [i.strip().split(',')[4] foriindata_]
ins_count=0ifnotdata_:
new_id=1else:
last=data_[-1]
last_id=int(last.split(',')[0])
new_id=last_id+1record=sql_dic.get('values').split('/')
foriinrecord:
ifi.split(',')[2] inphone_list:
print('\033[1;31m%s 手机号已存在\033[0m'%i)
else:
new_record='\n%s,%s\n'% (str(new_id), i)
fp.write(new_record)
new_id+=1ins_count+=1fp.flush()  # 刷新记录return ['insert successfully!'], [str(ins_count)]
defdelete(sql_dic, item):
"""    处理delete语句命令    :param sql_dic:    :param item:    :return:    """withopen(data_path, 'r', encoding='utf-8') asr_file, \
open('staff_data_bak.txt', 'w', encoding='utf-8') asw_file:
del_count=0# delete from staff_data.txt where staff_id>=5 and staff_id<=10forlineinr_file.read().split("\n")[1:]:
# print(line)dic=dict(zip(item.split(','), line.split(',')))
# print(dic)# delete from staff_data.txt where staff_id>=5 and staff_id<=10print(dic)
print(sql_dic.get("where"))
# exp_1, opt, exp_2 = sql_dic.get("where")record_list= []
try:
foriteminsql_dic.get("where"):
print(item)
iftype(item) islist:
exp_1, opt, exp_2=itemprint(exp_1, opt, exp_2)
flag=eval(f'{dic["staff_id"]}{opt}{exp_2}')
print(flag)
record_list.append(flag)
print(all(record_list), record_list)
ifall(record_list):  # 删除满足条件的del_count+=1passelse:
w_file.write(line+"\n")
exceptExceptionase:
print(e.args[0])
passw_file.flush()
# os.remove('staff_data.txt')# os.rename('staff_data_bak.txt', 'staff_data.txt')return ['delete successfully!'], [str(del_count)]
defupdate(sql_dic, title_):
"""    处理update语句命令    :param sql_dic:    :param title_:    :return:    """set_l=sql_dic.get('set').strip().split(',')
set_list= [i.split('=') foriinset_l]
update_count=0withopen(data_path, 'r', encoding='utf-8') asr_file, \
open('staff_data_bak.txt', 'w', encoding='utf-8') asw_file:
forlineinr_file:
dic=dict(zip(title_.split(','), line.strip().split(',')))
filter_res=logic_action(dic, sql_dic.get('where'))
iffilter_res:
foriinset_list:
k=i[0]
v=i[-1]
dic[k] =vline= [dic[i] foriintitle_.split(',')]
update_count+=1line=','.join(line) +'\n'w_file.write(line)
w_file.flush()
os.remove('staff_data.txt')
os.rename('staff_data_bak.txt', 'staff_data.txt')
return ['update successfully!'], [str(update_count)]
defwhere_action(fh, where_list, title_):
"""    具体处理where_list里的所有条件    :param fh:    :param where_list:    :param title_:    :return:    """res= []
iflen(where_list) !=0:
forlineinfh:
dic=dict(zip(title_.split(','), line.strip().split(',')))
ifdic['name'] !='name':
logic_res=logic_action(dic, where_list)
iflogic_res:
res.append(line.strip().split(','))
else:
res= [i.split(',') foriinfh.readlines()]
returnresdeflogic_action(dic, where_list):
"""    判断数据文件中每一条是否符合where_list条件    :param dic:    :param where_list:    :return:    """logic= []
# print(where_list)# print(dic)forexpinwhere_list:
# print(exp)iftype(exp) islist:
exp_k, opt, exp_v=exp# print(exp_k, opt, exp_v)ifexp[1] =='=':
opt='=='logical_char="'%s'%s'%s'"% (dic[exp_k], opt, exp_v)
# print(logical_char)ifopt!='like':
exp=str(eval(logical_char))
else:
ifexp_vindic[exp_k]:
exp='True'else:
exp='False'logic.append(exp)
res=eval(' '.join(logic))
returnresdeflimit_action(filter_res, limit_l):
"""    用列表切分处理显示符合条件的数量    :param filter_res:    :param limit_l:    :return:    """iflimit_l:
index=int(limit_l[0])
res=filter_res[:index]
else:
res=filter_resreturnresdefsearch_action(limit_res, select_list, title_):
"""    处理需要查询并显示的title和相应数据    :param limit_res:    :param select_list:    :param title_:    :return:    """res= []
fields_list_=title_.split(',')
ifselect_list[0] =='*':
res=limit_reselse:
fields_list_=select_listfordata_inlimit_res:
dic=dict(zip(title_.split(','), data_))
r_l= []
foriinfields_list_:
r_l.append((dic[i].strip()))
res.append(r_l)
returnfields_list_, res


主函数调用


if__name__=='__main__':
# 指令关键词列表key_lis= ['select', 'insert', 'delete', 'update', 'from', 'into', 'set', 'values', 'where', 'limit']
whileTrue:
sql=input('请输入sql命令,退出请输入exit->>>').strip()
sql=re.sub(' ', '', sql)
iflen(sql) ==0:
continueifsql=='exit':
breaksql_dict=sql_parse(sql, key_lis)
try:
data_path=sql_dict['from']
exceptKeyError:
data_path=sql_dict['into']
withopen(data_path, 'r', encoding='utf-8') asf:
title=f.readline().strip()
fields_list, fields_data=sql_action(sql_dict, title)
print('\033[0;32m结果如下:\033[0m')
print('-'.join(fields_list))
fordatainfields_data:
print('-'.join(data))


三、测试结果


# 测试sql命令如下:# select * from staff_data.txt where dept=人事# select name,age from staff_data.txt where age > 27# select * from staff_data.txt where enroll_date like 2017# insert into staff_data.txt values 叶庭云,21,13198497869,算法,2018-7-12# update into staff_data.txt set dept=算法,phone=13566677787 where staff_id=8# delete from staff_data.txt where staff_id>=5 and staff_id<=10# delete from staff_data.txt where staff_id>=5 and staff_id<=10




所有测试结果如下:



推荐阅读:

https://www.cnblogs.com/JayeHe/p/6846524.html

https://www.jb51.net/article/117919.htm

目录
相关文章
|
6天前
|
安全 Python
告别低效编程!Python线程与进程并发技术详解,让你的代码飞起来!
【7月更文挑战第9天】Python并发编程提升效率:**理解并发与并行,线程借助`threading`模块处理IO密集型任务,受限于GIL;进程用`multiprocessing`实现并行,绕过GIL限制。示例展示线程和进程创建及同步。选择合适模型,注意线程安全,利用多核,优化性能,实现高效并发编程。
20 3
|
6天前
|
数据采集 大数据 数据安全/隐私保护
Python编程:如何有效等待套接字的读取与关闭
Python网络编程中,套接字事件处理至关重要。利用`selectors`模块和代理IP能增强程序的稳定性和可靠性。代码示例展示了如何通过代理连接目标服务器,注册套接字的读写事件并高效处理。在代理IP配置、连接创建、事件循环及回调函数中,实现了数据收发与连接管理,有效应对网络爬虫或聊天应用的需求,同时保护了真实IP。
Python编程:如何有效等待套接字的读取与关闭
|
2天前
|
SQL API Python
`bandit`是一个Python静态代码分析工具,专注于查找常见的安全漏洞,如SQL注入、跨站脚本(XSS)等。
`bandit`是一个Python静态代码分析工具,专注于查找常见的安全漏洞,如SQL注入、跨站脚本(XSS)等。
19 8
|
1天前
|
数据挖掘 开发者 Python
如何自学Python编程?
【7月更文挑战第14天】如何自学Python编程?
16 4
|
4天前
|
Python
不容错过!Python中图的精妙表示与高效遍历策略,提升你的编程艺术感
【7月更文挑战第11天】在Python编程中,图以邻接表或邻接矩阵表示,前者节省空间,后者利于查询连接。通过字典实现邻接表,二维列表构建邻接矩阵。图的遍历包括深度优先搜索(DFS)和广度优先搜索(BFS)。DFS使用递归,BFS借助队列。这些基础技巧对于解决复杂数据关系问题,如社交网络分析或迷宫求解,至关重要,能提升编程艺术。
13 5
|
6天前
|
存储 算法 Python
震撼!Python算法设计与分析,分治法、贪心、动态规划...这些经典算法如何改变你的编程世界!
【7月更文挑战第9天】在Python的算法天地,分治、贪心、动态规划三巨头揭示了解题的智慧。分治如归并排序,将大问题拆解为小部分解决;贪心算法以局部最优求全局,如Prim的最小生成树;动态规划通过存储子问题解避免重复计算,如斐波那契数列。掌握这些,将重塑你的编程思维,点亮技术之路。
14 1
|
6天前
|
SQL 关系型数据库 MySQL
【Python】已解决:ERROR 1064 (42000): You have an error in your SQL syntax. check the manual that correspo
【Python】已解决:ERROR 1064 (42000): You have an error in your SQL syntax. check the manual that correspo
21 0
|
6天前
|
算法 调度 索引
Python堆与优先队列大起底:深入骨髓的解析,让你彻底告别低效编程!
【7月更文挑战第9天】Python的heapq模块实现了堆数据结构,提供heappush和heappop等操作,支持最小堆。堆是完全二叉树,满足堆属性。优先队列利用堆实现,元素按优先级出队。通过将优先级和元素打包入堆,如示例所示,能轻松处理优先级任务。掌握堆与优先队列,提升编程效率。
11 0
|
安全 数据安全/隐私保护 Python
Python初级案例教学【第二课】(Python 黑客对讲机,模拟个人用户登录,银行金额大写汉字转换)
Python模拟个人用户登录 业务需求: 要求:账号:admin 密码:123 1.登录时给3次机会。 2. 如果成功,显示欢迎xxx。 3. 如果登录失败,显示录入错误你还有x次机会。如果3次机会使用完毕,则显示登录超限,请明天再登录。 Python银行金额大写汉字转换 业务需求: 银行电子支票业务在金额部分需要使用大写的汉字,因此需要将用户录入的数字信息转变为汉字。 • 目前只需完成1~5位整数转换即可。
291 1
Python初级案例教学【第二课】(Python 黑客对讲机,模拟个人用户登录,银行金额大写汉字转换)
|
Python
python模拟用户登录某某网
python模拟用户登录某某网: #encoding:utf-8 import urllib2,cookielib import re #在网页登陆成功后的cookies字符串 cookie="|utmccn=(referral)|utmcmd=...
861 0