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.流程图

4.代码

 #!usr/bin/env python3
#_*_coding:utf-8_*_ 'staff infomation management module'
__author__='Byron Li' '''----------------------------------------------员工信息数据库操作指令语法---------------------------------------------
数据记录包含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 * #显示所有记录
---------------------------------------------------------------------------------------------------------------------'''
import re
import os
class staff(object): #员工类
def __init__(self,*args): #员工信息初始化:从字符串列表传参赋值
self.id=args[0]
self.name=args[1]
self.age=args[2]
self.phone=args[3]
self.dept=args[4]
self.enroll_date=args[5]
self.allinfo=','.join(args)
def update(self,**kwargs): #员工信息更新:从字典传参赋值
if 'id' in kwargs:
self.id=kwargs['id']
if 'name' in kwargs:
self.name=kwargs['name']
if 'age' in kwargs:
self.age = kwargs['age']
if 'phone' in kwargs:
self.phone=kwargs['phone']
if 'dept' in kwargs:
self.dept=kwargs['dept']
if 'enroll_date' in kwargs:
self.enroll_date = kwargs['enroll_date']
self.allinfo = ','.join(map(str,[self.id, self.name, self.age, self.phone, self.dept, self.enroll_date]))
def print_info(self,info): #员工信息打印显示:传入的参数为"*"或数据记录的若干个关键字
if info=='*':
print(self.allinfo)
else:
info=info.split(',')
res=[]
for i in info:
if hasattr(self,i.strip()):
res.append(str(getattr(self,i.strip())))
print(','.join(res)) def command_exe(command): #指令执行主函数,根据指令第一个字段识别何种操作,并分发给相应的处理函数执行
command=command.strip()
return {
'add':add,
'delete':delete,
'update':update,
'select':search,
}.get(command.split()[0],error)(command) def error(command): #错误提示函数,指令不合语法调用该函数报错
print('\033[31;1m语法错误,请重新输入!\033[0m\n') def add(command): #增加员工记录函数
command_parse=re.search(r'add\s*?to\s(.*?)values\s(.*)',command) #正则表达式指令解析
if(command_parse):
data_file=command_parse.group(1).strip() #数据库文件
info=command_parse.group(2).strip() #需新增的员工信息,不含id
id=1 #新增员工id,默认为1以防数据库为空表时新增记录id取1
with open(data_file, 'r+', encoding='utf-8') as fr:
line=fr.readline()
while(line):
if line.strip()=='':
fr.seek(fr.tell()-len(line)-2) #定位文件最后一行(只有空字符)的开头
break
staff_temp = staff(*line.strip().split(',')) #读取的信息转换为staff对象
id = int(staff_temp.id) + 1 #末行员工id加1为新员工id
line = fr.readline()
info_new=''.join([str(id),',',info]) #id与其他信息合并成完整记录
fr.write(info_new)
fr.write('\n')
fr.flush()
print("数据库本次\033[31;1m新增1条\033[0m员工信息:", info_new) #新增记录打印
else:
error(command) def delete(command): #删除员工记录函数
command_parse=re.search(r'delete\s*?from\s(.*?)where\s(.*)',command) #指令解析
if(command_parse):
data_file=command_parse.group(1).strip() #数据库文件
condition=command_parse.group(2).strip() #检索条件
data_file_bak = ''.join([data_file, '.bak'])
count = 0 #删除记录计数
staff_list = [] #删除记录的员工对象列表
with open(data_file, 'r', encoding='utf-8') as fr, \
open(data_file_bak, 'w', encoding='utf-8') as fw:
for line in fr:
staff_temp = staff(*line.strip().split(','))
if (verify(staff_temp, condition)): #验证员工信息是否符合条件
count+=1
staff_list.append(staff_temp)
continue
fw.write(staff_temp.allinfo)
fw.write('\n')
fw.flush()
os.remove(data_file)
os.rename(data_file_bak, data_file)
print("数据库本次共\033[31;1m删除%d条\033[0m员工信息,如下:"%count)
for staff_temp in staff_list:
staff_temp.print_info('*') #删除记录打印
else:
error(command) def update(command): #修改和更新员工记录函数
command_parse=re.search(r'update\s(.*?)set\s(.*?)where\s(.*)',command) #指令解析
if(command_parse):
data_file=command_parse.group(1).strip() #数据库文件
info=command_parse.group(2).strip() #需更新的信息
condition=command_parse.group(3).strip() #检索条件
data_file_bak=''.join([data_file,'.bak']) info = ''.join(['{', info.replace('=', ':'), '}']) #将需更新的信息按字典格式修饰字符串
info = eval(re.sub(r'(\w+)\s*:', r'"\1":', info)) #将字符串进一步修饰最终转化成字典
count = 0
staff_list = []
with open(data_file,'r',encoding='utf-8') as fr,\
open(data_file_bak,'w',encoding='utf-8') as fw:
for line in fr:
staff_temp=staff(*line.strip().split(','))
if(verify(staff_temp,condition)): #验证员工信息是否符合条件
staff_temp.update(**info) #调用员工对象成员函数更新信息
count += 1
staff_list.append(staff_temp)
fw.write(staff_temp.allinfo)
fw.write('\n')
fw.flush()
os.remove(data_file)
os.rename(data_file_bak,data_file)
print("数据库本次共\033[31;1m更新%d条\033[0m员工信息,如下:"%count)
for staff_temp in staff_list:
staff_temp.print_info('*') #更新记录打印
else:
error(command) def search(command): #查询员工记录函数
command_parse=re.search(r'select\s(.*?)from\s(.*?)where\s(.*)',command) #指令解析
if(command_parse):
info=command_parse.group(1).strip() #检索结束后需显示的信息,"*"为显示整体记录
data_file=command_parse.group(2).strip() #数据库文件
condition=command_parse.group(3).strip() #检索条件
count = 0
staff_list = []
with open(data_file,'r',encoding='utf-8') as fr:
for line in fr:
staff_temp=staff(*line.strip().split(','))
if(verify(staff_temp,condition)): #验证员工信息是否符合条件
count += 1
staff_list.append(staff_temp)
print("数据库本次共\033[31;1m查询到%d条\033[0m员工信息,如下:" % count)
for staff_temp in staff_list:
staff_temp.print_info(info) #查询记录打印
else:
error(command) def verify(staff_temp,condition): #员工信息验证函数,传入一个员工对象和条件字符串
if condition.strip()=='*':return True #如果条件为'*',即所有记录都满足条件
condition_list=condition.split() #检索条件字符串转列表
if len(condition_list)==0:return False
logic_str=['and','or','not'] #逻辑运算字符串 且、或、非
logic_exp=[] #单个条件的逻辑表达式组成的列表,形如[‘age',' ','>','=',20] 或 [‘dept',' ','like',' ','HR']
logic_list=[] #每个条件的表达式的计算结果再重组后的列表,形如 [‘True','and','False','or','not','False']
for i in condition_list:
if i in logic_str:
if(len(logic_exp)!=0):
logic_list.append(str(logic_cal(staff_temp,logic_exp))) #逻辑表达式计算并将返回的True或False转化成字符串添加到列表
logic_list.append(i)
logic_exp=[]
else:
logic_exp.append(i)
logic_list.append(str(logic_cal(staff_temp, logic_exp)))
return eval(' '.join(logic_list)) #列表转化成数学表达式完成所有条件的综合逻辑运算,结果为True或False def logic_cal(staff_temp,logic_exp): #单个逻辑表达式的运算函数
logic_exp = re.search('(.+?)([=<>]{1,2}|like)(.+)',''.join(logic_exp)) #表达式列表优化成三个元素,形如[‘age','>=',20] 或 [‘dept','like','HR']
if(logic_exp):
logic_exp=list(logic_exp.group(1,2,3))
if(hasattr(staff_temp,logic_exp[0])):
logic_exp[0] = getattr(staff_temp,logic_exp[0])
else:
return False
if logic_exp[1]=='=': #指令中的'='转化成程序中相等判别的"=="
logic_exp[1]='=='
if logic_exp[1]=='like': #运算符为like的表达式运算
return re.search(logic_exp[2].strip("'").strip('"'),logic_exp[0]) and True
elif(logic_exp[0].isdigit() and logic_exp[2].isdigit()): #两头为数字的运算,直接eval函数转数学表达式
return eval(''.join(logic_exp))
elif(logic_exp[1]=='=='): #非数字的运算,即字符串运算,此时逻辑符只可能是‘=’,若用eval函数则字符串会转成无定义变量而无法计算,所以拿出来单独用"=="直接计算
return logic_exp[0]==logic_exp[2].strip("'").strip('"') #字符串相等判别,同时消除指令中字符串引号的影响,即输引号会比记录中的字符串多一层引号
else: #其他不合语法的条件格式输出直接返回False
return False
else:
return False if __name__=='__main__': #主函数,数据库指令输入和执行
while(True):
command=input("请按语法输入数据库操作指令:") #指令输入
if command=='exit':
print("数据库操作结束,成功退出!".center(50, '*'))
break
command_exe(command) #指令执行

Python程序练习4--模拟员工信息数据库操作的更多相关文章

  1. jQuery实现的3个基础案例(仿QQ列表分组,二级联动下拉框,模拟员工信息管理系统)

    1.仿QQ列表分组 <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type&quo ...

  2. Python学习笔记:sqlite3(sqlite数据库操作)

    对于数据库的操作,Python中可以通过下载一些对应的三方插件和对应的数据库来实现数据库的操作,但是这样不免使得Python程序变得更加复杂了.如果只是想要使用数据库,又不想下载一些不必要的插件和辅助 ...

  3. Python框架学习之Flask中的数据库操作

    数据库操作在web开发中扮演着一个很重要的角色,网站中很多重要的信息都需要保存到数据库中.如用户名.密码等等其他信息.Django框架是一个基于MVT思想的框架,也就是说他本身就已经封装了Model类 ...

  4. python学习笔记(15)pymysql数据库操作

    pymysql数据库操作 1.什么是PyMySQL 为了使python连接上数据库,你需要一个驱动,这个驱动是用于与数据库交互的库. PyMySQL : 这是一个使Python连接到MySQL的库,它 ...

  5. Python开发【十一章】:数据库操作Memcache、Redis

    一.Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的 ...

  6. python作业员工信息表程序(第四周)

    作业需求: 1. 员工信息表程序,实现增删改查操作: 2. 可进行模糊查询,语法至少支持下面3种: select name,age from staff_table where age > 22 ...

  7. Python进行MySQL数据库操作

    最近开始玩Python,慢慢开始喜欢上它了,以前都是用shell来实现一些自动化或者监控的操作,现在用Python来实现,感觉更棒,Python是一门很强大的面向对象语言,所以作为一个运维DBA或者运 ...

  8. nodejs 数据库操作,消息的发送和接收,模拟同步

    var deasync = require('deasync'); //导入模板 var mysql=require('mysql'); var Stomp = require('stompjs'); ...

  9. python练习程序_员工信息表_基本实例

    python实现增删改查操作员工信息文件,可进行模糊查询: http://edu.51cto.com/lesson/id-13276.html http://edu.51cto.com/lesson/ ...

随机推荐

  1. 201521123053《Java程序设计》第四周总结

    1. 本周学习总结 1.1 尝试使用思维导图总结有关继承的知识点. 1.2 使用常规方法总结其他上课内容. 现在上课跟着老师的思路走,一般都能理解了.就是课上知识点有些难以记住. 特别讲讲这个思维导图 ...

  2. java向前引用

    根据看书和看得文章,引出了一个关于"向前引用"的问题: public class InstanceInitTest { static { // { a = 6; System.ou ...

  3. 泛型在Web中的作用

    当我们写网页的时候,常常会有多个DAO,我们要写每次都要写好几个DAO,这样会有点麻烦. 那么我们想要的效果是什么呢??只写一个抽象DAO,别的DAO只要继承该抽象DAO,就有对应的方法了. 要实现这 ...

  4. svn服务器配置与客户端的使用

    1, Apache Subversion 官网下载地址: http://subversion.apache.org/packages.html#windows 官网下载提供的一般都是最新版本的,如果想 ...

  5. springmvc04-文件上传-JSON数据

    文件上传部分: 1, 导入commons-fileupload-1.2.2.jar commons-io-2.4.jar 两个jar包. 2, 在主配置文件中,添加如下信息 <!-- 文件上传- ...

  6. Linux 环境下 MySQ导入和导出MySQL的sql文件

    将服务器上的文件导入或导出还需要使用工具传输到本机中,推荐使用winscp,与xshell搭配使用 1 导入数据库 两种方法 .首先建空数据库 mysql>create database abc ...

  7. 王者荣耀是怎样炼成的(三)unity组件与脚本

    转载请注明出处:http://www.cnblogs.com/yuxiuyan/p/7565345.html 上回书说到了unity的基本操作.这回我们来侃侃unity中的组件与脚本. 目录结构 一. ...

  8. [python学习笔记] String格式化

    格式化 S % (args...) 方式 特点 str里的占位符同java里的占位符. 优势 这种方式可以限定格式化的时候接受的数据类型. 常见占位符 %d 接收数字,格式化为 十进制 %x 接收数字 ...

  9. GCD之barrier

    1.在并行队列执行任务中,如果想让某一个任务先执行完后再执行其后面的任务,此时可以用dispatch_barrier_async,下图是dispatch_barrier_async函数的处理流程. 2 ...

  10. 再起航,我的学习笔记之JavaScript设计模式25(迭代器模式)

    迭代器模式 概念介绍 迭代器模式(Iterator): 在不暴露对象内部结构的同时,可以顺序地访问聚合对象内部的元素. 迭代器 程序中的循环是一种利器,循环语句也使我们程序开发更简洁高效,但是有时一遍 ...