国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python 模擬員工信息數據庫操作的實例

2020-01-04 16:38:17
字體:
來源:轉載
供稿:網友

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

Python,數據庫,員工信息表

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,not1.增(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 reimport osclass 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或Falsedef 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 Falseif __name__=='__main__':  #主函數,數據庫指令輸入和執行 while(True):  command=input("請按語法輸入數據庫操作指令:") #指令輸入  if command=='exit':   print("數據庫操作結束,成功退出!".center(50, '*'))   break  command_exe(command)  #指令執行

以上這篇Python 模擬員工信息數據庫操作的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 随州市| 道真| 乌拉特后旗| 潼南县| 布尔津县| 毕节市| 九寨沟县| 曲水县| 广宁县| 康平县| 牡丹江市| 阳朔县| 大足县| 日照市| 兴仁县| 佳木斯市| 夏邑县| 梨树县| 光山县| 大庆市| 深圳市| 平山县| 垦利县| 昭觉县| 仲巴县| 临泽县| 视频| 平凉市| 楚雄市| 株洲县| 桐庐县| 乌鲁木齐县| 大厂| 昌都县| 无锡市| 杂多县| 溧阳市| 高陵县| 乌兰县| 东山县| 元江|