写一个简单的员工信息增删改查程序,需求如下:
当然此表你在文件存储时可以这样表示
1,Alex Li,22,13651054608,IT,2013-04-01 2,Jack Wang,28,13451024608,HR,2015-01-07 3,Rain Wang,21,13451054608,IT,2017-04-01 4,Mack Qiao,44,15653354208,Sales,2016-02-01 5,Rachel Chen,23,13351024606,IT,2013-03-16 6,Eric Liu,19,18531054602,Marketing,2012-12-01 7,Chao Zhang,21,13235324334,Administration,2011-08-08 8,Kevin Chen,22,13151054603,Sales,2013-04-01 9,Shit Wen,20,13351024602,IT,2017-07-03 10,Shanshan Du,26,13698424612,Operation,2017-07-02
1.可进行模糊查询,语法至少支持下面3种查询语法:
find name,age from staff_table where age > 22 find * from staff_table where dept = "IT" find * from staff_table where enroll_date like "2013"
2.可创建新员工纪录,以phone做唯一键(即不允许表里有手机号重复的情况),staff_id需自增
语法: add staff_table Alex Li,25,134435344,IT,2015-10-29
3.可删除指定员工信息纪录,输入员工id,即可删除
语法: del from staff_table where id=3
4.可修改员工信息,语法如下:
UPDATE staff_table SET dept="Market" WHERE dept = "IT" 把所有dept=IT的纪录的dept改成Market UPDATE staff_table SET age=25 WHERE name = "Alex Li" 把name=Alex Li的纪录的年龄改成25
5.以上每条语名执行完毕后,要显示这条语句影响了多少条纪录。 比如查询语句 就显示 查询出了多少条、修改语句就显示修改了多少条等。
----------------------------------------------------------------
----------------------------------------------------------------
标准答案:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # _*_coding:utf-8_*_ 2 # created by Alex Li on 10/15/17 3 from tabulate import tabulate 4 import os 5 6 STAFF_DB = "staff.db" #因为不会变,所以是常量 7 COLUMN_ORDERS = ['id','name','age','phone','dept','enrolled_date'] 8 9 10 11 def load_db(): 12 """ 13 打开db文件,把文件里的数据的每列转换成一个列表 14 1,Alex Li,22,13651054608,IT,2013-04-01 15 16 :return: 17 """ 18 staff_data = { #把文件里的每列添加到下面这些列表里 19 'id':[], 20 'name':[], 21 'age':[], 22 'phone':[], 23 'dept':[], 24 'enrolled_date':[] 25 } 26 27 28 f = open(STAFF_DB,"r",encoding="utf-8") 29 30 for line in f: 31 staff_id,name,age,phone,dept,enrolled_date = line.strip().split(',') 32 staff_data['id'].append(staff_id) 33 staff_data['name'].append(name) 34 staff_data['age'].append(age) 35 staff_data['phone'].append(phone) 36 staff_data['dept'].append(dept) 37 staff_data['enrolled_date'].append(enrolled_date) 38 39 #print(staff_data) 40 f.close() 41 return staff_data 42 43 44 def save_db(): 45 """sync data back to db each time after editing""" 46 f = open("%s_tmp"%STAFF_DB, "w", encoding="utf-8") 47 48 for index,val in enumerate(STAFF_DATA[COLUMN_ORDERS[0]]): 49 row = [str(val)] 50 for col in COLUMN_ORDERS[1:]: 51 row.append(str(STAFF_DATA[col][index]) ) 52 53 raw_row = ",".join(row) 54 f.write(raw_row+" ") 55 f.close() 56 os.rename("%s_tmp"%STAFF_DB,STAFF_DB) 57 58 59 def print_log(msg,msg_type='info'): 60 if msg_type == 'error': 61 print("