1.功能简介

此程序模拟员工信息数据库操作,按照语法输入指令即能实现员工信息的增、删、改、查功能。

2.实现方法

• 架构:

本程序采用python语言编写,关键在于指令的解析和执行:其中指令解析主要运用了正则表达式来高效匹配有效信息;指令执行通过一个commd_exe主执行函数和增、删、改、查4个子执行函数来实现,操作方法主要是运用面向对象方法将员工信息对象化,从而使各项操作都能方便高效实现。程序主要函数如下:

(1)command_exe(command)

指令执行主函数,根据指令第一个字段识别何种操作,并分发给相应的处理函数执行。

(2)add(command)

增加员工记录函数,指令中需包含新增员工除id号以外的其他所有信息,程序执行后信息写入员工信息表最后一行,id号根据原最后一条记录的id号自增1。

(3)delete(command)

删除员工记录函数,可根据where后的条件检索需删除的记录,并从信息表中删除。

(4)update(command)

修改和更新员工记录函数,根据where后的条件检索需更新的记录,根据set后的等式修改和更新指定的信息。

(5)search(command)

查询员工记录函数,根据where后的条件查询到相应的记录,根据select后的关键字来显示记录的指定信息,如果为*显示记录的所有信息。

(6)verify(staff_temp,condition)

员工信息验证函数,传入一个对象化的员工记录和指令中where后的条件字符串,判断记录是否符合条件,符合在返回True,否则返回False。指令包含where字段的删、改、查操作会调用此函数。

(7)logic_cal(staff_temp,logic_exp)

单个逻辑表达式的运算函数,传入一个对象化的员工记录和从where条件字符串中被and、or、not分割的单个表达式,实现=,>,<,>=,<=,like等确定的一个逻辑表达式的运算,返回结果为True或False。

• 主要操作:

数据记录包含6个关键字:id,name,age,phone,dept,enroll_date

指令可用的逻辑运算符:<,>,=,<=,>=,like,and,or,not

数据库操作:

1.增(add to xxxx values xxxx)

示例:add to staff_table values Alex Li,22,13651054608,IT,2013-04-01

2.删(delete from xxxx where xxxx)

示例:delete from staff_table where age<=18 and enroll_date like “2017”

3.改(update xxxx set xxxx where xxxx)

示例:

update staff_table set dept=”Market”,age=30 where dept=”IT” and phone like “189”

4.查(select xxxx from xxxx where xxxx)

示例1:

select * from staff_table where age>=25 and not phone like “136” or name like “李”

示例2:

select name,age,dept from db.txt where id<9 and enroll_date like “-05-“

示例3:select from staff_table where #显示所有记录

•使用文件:

staff_table

存放员工信息表,作为模拟的数据库文件,每条记录包含id,name,age,phone,dept,enroll_date六项信息,如”1,Alex Li,22,13651054608,IT,2013-04-0”。

3.流程图
http://zsrimg.ikafan.com/file_images/article/201710/2017102309205217.jpg
4.代码

  1. #!usr/bin/env python3
  2. #_*_coding:utf-8_*_
  3. 'staff infomation management module'
  4. __author__='Byron Li'
  5. '''----------------------------------------------员工信息数据库操作指令语法---------------------------------------------
  6. 数据记录包含6个关键字:id,name,age,phone,dept,enroll_date
  7. 指令可用的逻辑运算符:<,>,=,<=,>=,like,and,or,not
  8. 1.增(add to xxxx values xxxx)
  9. 示例:add to staff_table values Alex Li,22,13651054608,IT,2013-04-01
  10. 2.删(delete from xxxx where xxxx)
  11. 示例:delete from staff_table where age<=18 and enroll_date like "2017"
  12. 3.改(update xxxx set xxxx where xxxx)
  13. 示例:update staff_table set dept="Market",age=30 where dept="IT" and phone like "189"
  14. 4.查(select xxxx from xxxx where xxxx)
  15. 示例1:select * from staff_table where age>=25 and not phone like "136" or name like "李"
  16. 示例2:select name,age,dept from db.txt where id<9 and enroll_date like "-05-"
  17. 示例3:select * from staff_table where * #显示所有记录
  18. ---------------------------------------------------------------------------------------------------------------------'''
  19. import re
  20. import os
  21. class staff(object): #员工类
  22. def __init__(self,*args): #员工信息初始化:从字符串列表传参赋值
  23. self.id=args[0]
  24. self.name=args[1]
  25. self.age=args[2]
  26. self.phone=args[3]
  27. self.dept=args[4]
  28. self.enroll_date=args[5]
  29. self.allinfo=','.join(args)
  30. def update(self,**kwargs): #员工信息更新:从字典传参赋值
  31. if 'id' in kwargs:
  32. self.id=kwargs['id']
  33. if 'name' in kwargs:
  34. self.name=kwargs['name']
  35. if 'age' in kwargs:
  36. self.age = kwargs['age']
  37. if 'phone' in kwargs:
  38. self.phone=kwargs['phone']
  39. if 'dept' in kwargs:
  40. self.dept=kwargs['dept']
  41. if 'enroll_date' in kwargs:
  42. self.enroll_date = kwargs['enroll_date']
  43. self.allinfo = ','.join(map(str,[self.id, self.name, self.age, self.phone, self.dept, self.enroll_date]))
  44. def print_info(self,info): #员工信息打印显示:传入的参数为"*"或数据记录的若干个关键字
  45. if info=='*':
  46. print(self.allinfo)
  47. else:
  48. info=info.split(',')
  49. res=[]
  50. for i in info:
  51. if hasattr(self,i.strip()):
  52. res.append(str(getattr(self,i.strip())))
  53. print(','.join(res))
  54. def command_exe(command): #指令执行主函数,根据指令第一个字段识别何种操作,并分发给相应的处理函数执行
  55. command=command.strip()
  56. return {
  57. 'add':add,
  58. 'delete':delete,
  59. 'update':update,
  60. 'select':search,
  61. }.get(command.split()[0],error)(command)
  62. def error(command): #错误提示函数,指令不合语法调用该函数报错
  63. print('\033[31;1m语法错误,请重新输入!\033[0m\n')
  64. def add(command): #增加员工记录函数
  65. command_parse=re.search(r'add\s*?to\s(.*?)values\s(.*)',command) #正则表达式指令解析
  66. if(command_parse):
  67. data_file=command_parse.group(1).strip() #数据库文件
  68. info=command_parse.group(2).strip() #需新增的员工信息,不含id
  69. id=1 #新增员工id,默认为1以防数据库为空表时新增记录id取1
  70. with open(data_file, 'r+', encoding='utf-8') as fr:
  71. line=fr.readline()
  72. while(line):
  73. if line.strip()=='':
  74. fr.seek(fr.tell()-len(line)-2) #定位文件最后一行(只有空字符)的开头
  75. break
  76. staff_temp = staff(*line.strip().split(',')) #读取的信息转换为staff对象
  77. id = int(staff_temp.id) + 1 #末行员工id加1为新员工id
  78. line = fr.readline()
  79. info_new=''.join([str(id),',',info]) #id与其他信息合并成完整记录
  80. fr.write(info_new)
  81. fr.write('\n')
  82. fr.flush()
  83. print("数据库本次\033[31;1m新增1条\033[0m员工信息:", info_new) #新增记录打印
  84. else:
  85. error(command)
  86. def delete(command): #删除员工记录函数
  87. command_parse=re.search(r'delete\s*?from\s(.*?)where\s(.*)',command) #指令解析
  88. if(command_parse):
  89. data_file=command_parse.group(1).strip() #数据库文件
  90. condition=command_parse.group(2).strip() #检索条件
  91. data_file_bak = ''.join([data_file, '.bak'])
  92. count = 0 #删除记录计数
  93. staff_list = [] #删除记录的员工对象列表
  94. with open(data_file, 'r', encoding='utf-8') as fr, \
  95. open(data_file_bak, 'w', encoding='utf-8') as fw:
  96. for line in fr:
  97. staff_temp = staff(*line.strip().split(','))
  98. if (verify(staff_temp, condition)): #验证员工信息是否符合条件
  99. count+=1
  100. staff_list.append(staff_temp)
  101. continue
  102. fw.write(staff_temp.allinfo)
  103. fw.write('\n')
  104. fw.flush()
  105. os.remove(data_file)
  106. os.rename(data_file_bak, data_file)
  107. print("数据库本次共\033[31;1m删除%d条\033[0m员工信息,如下:"%count)
  108. for staff_temp in staff_list:
  109. staff_temp.print_info('*') #删除记录打印
  110. else:
  111. error(command)
  112. def update(command): #修改和更新员工记录函数
  113. command_parse=re.search(r'update\s(.*?)set\s(.*?)where\s(.*)',command) #指令解析
  114. if(command_parse):
  115. data_file=command_parse.group(1).strip() #数据库文件
  116. info=command_parse.group(2).strip() #需更新的信息
  117. condition=command_parse.group(3).strip() #检索条件
  118. data_file_bak=''.join([data_file,'.bak'])
  119. info = ''.join(['{', info.replace('=', ':'), '}']) #将需更新的信息按字典格式修饰字符串
  120. info = eval(re.sub(r'(\w+)\s*:', r'"\1":', info)) #将字符串进一步修饰最终转化成字典
  121. count = 0
  122. staff_list = []
  123. with open(data_file,'r',encoding='utf-8') as fr,\
  124. open(data_file_bak,'w',encoding='utf-8') as fw:
  125. for line in fr:
  126. staff_temp=staff(*line.strip().split(','))
  127. if(verify(staff_temp,condition)): #验证员工信息是否符合条件
  128. staff_temp.update(**info) #调用员工对象成员函数更新信息
  129. count += 1
  130. staff_list.append(staff_temp)
  131. fw.write(staff_temp.allinfo)
  132. fw.write('\n')
  133. fw.flush()
  134. os.remove(data_file)
  135. os.rename(data_file_bak,data_file)
  136. print("数据库本次共\033[31;1m更新%d条\033[0m员工信息,如下:"%count)
  137. for staff_temp in staff_list:
  138. staff_temp.print_info('*') #更新记录打印
  139. else:
  140. error(command)
  141. def search(command): #查询员工记录函数
  142. command_parse=re.search(r'select\s(.*?)from\s(.*?)where\s(.*)',command) #指令解析
  143. if(command_parse):
  144. info=command_parse.group(1).strip() #检索结束后需显示的信息,"*"为显示整体记录
  145. data_file=command_parse.group(2).strip() #数据库文件
  146. condition=command_parse.group(3).strip() #检索条件
  147. count = 0
  148. staff_list = []
  149. with open(data_file,'r',encoding='utf-8') as fr:
  150. for line in fr:
  151. staff_temp=staff(*line.strip().split(','))
  152. if(verify(staff_temp,condition)): #验证员工信息是否符合条件
  153. count += 1
  154. staff_list.append(staff_temp)
  155. print("数据库本次共\033[31;1m查询到%d条\033[0m员工信息,如下:" % count)
  156. for staff_temp in staff_list:
  157. staff_temp.print_info(info) #查询记录打印
  158. else:
  159. error(command)
  160. def verify(staff_temp,condition): #员工信息验证函数,传入一个员工对象和条件字符串
  161. if condition.strip()=='*':return True #如果条件为'*',即所有记录都满足条件
  162. condition_list=condition.split() #检索条件字符串转列表
  163. if len(condition_list)==0:return False
  164. logic_str=['and','or','not'] #逻辑运算字符串 且、或、非
  165. logic_exp=[] #单个条件的逻辑表达式组成的列表,形如[‘age',' ','>','=',20] 或 [‘dept',' ','like',' ','HR']
  166. logic_list=[] #每个条件的表达式的计算结果再重组后的列表,形如 [‘True','and','False','or','not','False']
  167. for i in condition_list:
  168. if i in logic_str:
  169. if(len(logic_exp)!=0):
  170. logic_list.append(str(logic_cal(staff_temp,logic_exp))) #逻辑表达式计算并将返回的True或False转化成字符串添加到列表
  171. logic_list.append(i)
  172. logic_exp=[]
  173. else:
  174. logic_exp.append(i)
  175. logic_list.append(str(logic_cal(staff_temp, logic_exp)))
  176. return eval(' '.join(logic_list)) #列表转化成数学表达式完成所有条件的综合逻辑运算,结果为True或False
  177. def logic_cal(staff_temp,logic_exp): #单个逻辑表达式的运算函数
  178. logic_exp = re.search('(.+?)([=<>]{1,2}|like)(.+)',''.join(logic_exp)) #表达式列表优化成三个元素,形如[‘age','>=',20] 或 [‘dept','like','HR']
  179. if(logic_exp):
  180. logic_exp=list(logic_exp.group(1,2,3))
  181. if(hasattr(staff_temp,logic_exp[0])):
  182. logic_exp[0] = getattr(staff_temp,logic_exp[0])
  183. else:
  184. return False
  185. if logic_exp[1]=='=': #指令中的'='转化成程序中相等判别的"=="
  186. logic_exp[1]='=='
  187. if logic_exp[1]=='like': #运算符为like的表达式运算
  188. return re.search(logic_exp[2].strip("'").strip('"'),logic_exp[0]) and True
  189. elif(logic_exp[0].isdigit() and logic_exp[2].isdigit()): #两头为数字的运算,直接eval函数转数学表达式
  190. return eval(''.join(logic_exp))
  191. elif(logic_exp[1]=='=='): #非数字的运算,即字符串运算,此时逻辑符只可能是‘=',若用eval函数则字符串会转成无定义变量而无法计算,所以拿出来单独用"=="直接计算
  192. return logic_exp[0]==logic_exp[2].strip("'").strip('"') #字符串相等判别,同时消除指令中字符串引号的影响,即输引号会比记录中的字符串多一层引号
  193. else: #其他不合语法的条件格式输出直接返回False
  194. return False
  195. else:
  196. return False
  197. if __name__=='__main__': #主函数,数据库指令输入和执行
  198. while(True):
  199. command=input("请按语法输入数据库操作指令:") #指令输入
  200. if command=='exit':
  201. print("数据库操作结束,成功退出!".center(50, '*'))
  202. break
  203. command_exe(command) #指令执行

更多相关文章

  1. Android(安卓)记录一个好用的文件存储操作工具类SDCardHelper
  2. Android:电话拨号器、呼叫记录、结束通话、Android显示单位
  3. android学习小结4
  4. Activity启动模式记录
  5. Android下SQLite3数据库操作笔记
  6. Android下SQLite3数据库操作笔记
  7. 2019-11-07 Android谷歌支付SDK集成问题记录
  8. 2.3.2 Android(安卓)Studio使用记录——2.快捷键大全
  9. Android(安卓)HLS协议相关记录及部分解析

随机推荐

  1. Linux(Debian)设置开机自启动脚本
  2. jira 4.2破解安装Linux和windows版
  3. ubuntu 16.04 设置选项里面找不到《打印
  4. 使用VNC完成远程调用图形化
  5. 手动制作mini linux详细步骤―之二
  6. [Linux] 总结各系统 双网卡绑定
  7. 请问同一软件为什么linux版的要比xp版的
  8. busybox1.19.3编译错误解决办法
  9. linux用户管理及用户权力下放
  10. 如何在windows 10的linux子系统中启动jup