首页 > 代码库 > python函数模拟mysql增删改查功能
python函数模拟mysql增删改查功能
import os list1 = [‘staff_id‘, ‘name‘, ‘age‘, ‘phone‘, ‘dept‘, ‘enroll_date‘] def staff_info(): #获取员工信息生成器函数 with open(‘staff_table.txt‘, ‘r‘, encoding=‘utf-8‘) as f: for line in f : x =line.split(‘,‘) staff_dic = {k: v for (k, v) in zip(list1,x)} yield staff_dic def select_func(select_content,start,middle,end): #查找函数 if middle == ‘=‘: middle = ‘==‘ if select_content == ‘*‘: content = list1 else: content = select_content.split(‘,‘) total_check = 0 for i in staff_info(): list = [] for j in content: list.append(i[j]) #查找需要列出的项 if middle == ‘like‘: l=len(end) if eval(i[start][:l] + ‘==‘ +end ): print(list) total_check+=1 else: s = i[start] e = end if eval("s"+middle+"e"): print(list) total_check+=1 print(‘相关查询共计%s‘%total_check) def insert_func(list): #添加功能函数,添加的内容以列表写入 with open(‘staff_table.txt‘,‘r+‘,encoding=‘utf-8‘) as f: #判断手机号是否重复,若重复报错退出 for line in f: if list[2] in line: print(‘err information‘) return #不重复的添加内容 f.seek(0) info=f.readlines() staff_id=info[-1].split(‘,‘) staff_id=int(staff_id[0])+1 f.seek(0,2) s=‘‘ for i in list: if type(i)==int: i=str(i) s=s+‘,‘+i f.write(str(staff_id)+s+‘\n‘) def delete_func(staff_id): #删除信息函数 with open(‘staff_table.txt‘,‘r+‘,encoding=‘utf_8‘) as f, open(‘new.txt‘,‘w‘,encoding=‘utf-8‘) as f1: for line in f: if staff_id == line[0]: line=‘‘ f1.write(line) os.remove(‘staff_table.txt‘) os.rename(‘new.txt‘,‘staff_table.txt‘) def modify_func(oldcontent,newcontent): #修改函数 with open(‘staff_table.txt‘,‘r+‘,encoding=‘utf_8‘) as f, open(‘new.txt‘,‘w‘,encoding=‘utf-8‘) as f1: for line in f: if oldcontent in line: line=line.replace(oldcontent,newcontent) f1.write(line) os.remove(‘staff_table.txt‘) os.rename(‘new.txt‘,‘staff_table.txt‘) def run_func(): #运行函数 while 1: cmd=input(‘>>>: ‘) if cmd == ‘quit‘: break else: cmd=cmd.split() if cmd[0] == ‘select‘: end=cmd[-1] start=cmd[-3] middle=cmd[-2] select_content=cmd[1] select_func(select_content,start,middle,end) elif cmd[0] == ‘insert‘: list=cmd[1].split(‘,‘) insert_func(list) elif cmd[0].lower() == ‘update‘: oldcontent=cmd[-1] newcontent=cmd[5] modify_func(oldcontent,newcontent) elif cmd[0] == ‘delete‘: staff_id=cmd[1] delete_func(staff_id) else: print(‘err input‘) run_func()
staff_table.txt 里的内容:
1,Alex Li,22,13651054608,IT,2013-04-01
2,Jack Wang,30,13304320533,HR,2015-05-03
3,Rain Liu,25,1383235322,Sales,2016-04-22
4,Mack Cao,40,1356145343,HR,2009-03-01
因能力有限,命令格式请遵循下列说明
- 查询命令格式:select age,name from satff_table where dept == IT/age > 20/其他条件
- 修改命令格式:update staff_table set dept = market where where dept = IT
- 增加命令格式:insert mona, 15, 13693041938, IT, 2016-09-04
- 删除命令格式:delete 1
python函数模拟mysql增删改查功能
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。