Python 操作文件模拟SQL语句功能

Python操作文件模拟SQL语句功能


一、需求

当然此表你在文件存储时可以这样表示

1,Alex Li,22,13651054608,IT,2013-04-01 现需要对这个员工信息文件,实现增删改查操作

1. 可进行模糊查询,语法至少支持下面3种:
    1. select name,age from staff_table where age > 22
    2. select  * from staff_table where dept = "IT"
    3. select  * from staff_table where enroll_date like "2013"
    4. 查到的信息,打印后,最后面还要显示查到的条数 
2. 可创建新员工纪录,以phone做唯一键,staff_id需自增
3. 可删除指定员工信息纪录,输入员工id,即可删除
4. 可修改员工信息,语法如下:
    1. UPDATE staff_table SET dept="Market" WHERE where dept = "IT"

注意:以上需求,要充分使用函数,请尽你的最大限度来减少重复代码!


二、实现流程

第一部分:SQL解析

  • 1.接收用户SQL
    • 判断用户输入是否为SQL
  • 2.SQL解析主函数sql_parse
    • 分发SQL给对应语句的函数来做解析
      • insert_parse
      • delete_parse
      • update_parse
      • select_parse
    • 解析后交给handle_parse,来控制返回
    • 解析SQL语句中的多条件
      • where_parse
      • three_parse
    • 返回解析后的SQL

第二部分:SQL执行

  • 1.接收解析后的SQL

  • 2.SQL执行主函数sql_action

    • 分发SQL给对应函数来执行
      • insert
      • delete
      • update
      • select
    • 执行SQL语句时的多条件
      • where_action
      • logic_action
      • limit_action
      • search_action
    • 返回执行SQL的结果

    三、图解

      

        

    四、代码

    

  1 #/usr/local/env python
  2 #_*_coding:utf-8_*_
  3 
  4 #第一部分:sql解析
  5 import os
  6 def sql_parse(sql): #用户输入sql 转成结构化的字典
  7     '''
  8     第一步:sql解析 流程
  9     1.收到 sql查询条件
 10     2.sql_parse 来分发要求给 select_parse
 11     3.select_parse 调用 handle_parse 解析sql
 12     4.handle_parse 返回解析sql后的结果 sql_dic 给 select_parse
 13     5.select_parse 把 sql_dic 返回给sql_parse
 14     sql_dic=sql_parse(sql) #用户输入sql 转成结构化的字典sql_dic
 15     sql语句四种操作格式:insert delete update select
 16     提取用户输入sql 的操作关键词 再进行分析和分发操作
 17     把sql字符串切分,提取命令信息,分发给具体解析函数去解析
 18     :param sql:用户输入的字符串
 19     :return:返回字典格式sql解析结果
 20     '''
 21     #sql命令操作 解析函数的字典  根据用户的命令来找相对应的函数
 22     parse_func={
 23         'insert':insert_parse,
 24         'delete':delete_parse,
 25         'update':update_parse,
 26         'select':select_parse,
 27     }
 28 
 29     #print('用户输入 sql str is : %s' %sql) #打印用户输入的sql
 30     sql_l=sql.split(' ') #按空格切割用户sql 成列表 方便提取命令信息
 31     func=sql_l[0] #取出用户的sql命令
 32 
 33     #判断用户输入的sql命令 是否在定义好的sql命令函数的字典里面,如果不在字典里面,则返回空
 34     res=''
 35     if func in parse_func:
 36         res=parse_func[func](sql_l) #把切割后的 用户sql的列表 传入对应的sql命令函数里
 37 
 38     return res
 39 
 40 def insert_parse(sql_l):
 41     '''
 42     定义insert语句的语法结构,执行sql解析操作,返回sql_dic
 43     :param sql:sql按照空格分割的列表
 44     :return:返回字典格式的sql解析结果
 45     '''
 46     sql_dic={
 47         'func':insert, #函数名
 48         'insert':[],   #insert选项,留出扩展
 49         'into':[],     #表名
 50         'values':[],   #
 51     }
 52     return handle_parse(sql_l,sql_dic)
 53 
 54 def delete_parse(sql_l):
 55     '''
 56     定义delete语句的语法结构,执行sql解析操作,返回sql_dic
 57     :param sql:sql按照空格分割的列表
 58     :return:返回字典格式的sql解析结果
 59     '''
 60     sql_dic = {
 61         'func': delete,
 62         'delete': [],  # delete选项,留出扩展
 63         'from': [],  # 表名
 64         'where': [],  # filter条件
 65     }
 66     return handle_parse(sql_l, sql_dic)
 67 
 68 def update_parse(sql_l):
 69     '''
 70     定义update语句的语法结构,执行sql解析操作,返回sql_dic
 71     :param sql:sql按照空格分割的列表
 72     :return:返回字典格式的sql解析结果
 73     '''
 74     sql_dic = {
 75         'func': update,
 76         'update': [],  # update选项,留出扩展
 77         'set': [],  # 修改的值
 78         'where': [],  # filter条件
 79     }
 80     return handle_parse(sql_l, sql_dic)
 81 
 82 def select_parse(sql_l):
 83     '''
 84     定义select语句的语法结构,执行sql解析操作,返回sql_dic
 85     :param sql:sql按照空格分割的列表
 86     :return:返回字典格式的sql解析结果
 87     '''
 88     # print('from in the select_parse :33[42;1m%s33[0m' %sql_l)
 89     # select语句多种条件查询,列成字典,不同条件不同列表
 90     sql_dic={
 91         'func':select, #执行select语句
 92         'select':[], #查询字段
 93         'from':[],   #数据库.表
 94         'where':[],  #filter条件,怎么找
 95         'limit':[],  #limit条件,限制
 96     }
 97     return handle_parse(sql_l,sql_dic)
 98 
 99 def handle_parse(sql_l,sql_dic): #专门做sql解析操作
100     '''
101     执行sql解析操作,返回sql_dic
102     :param sql_l: sql按照空格分割的列表
103     :param sql_dic: 待填充的字典
104     :return: 返回字典格式的sql解析结果
105     '''
106     # print('sql_l is 33[41;1m%s33[0m 
sql_dic is 33[41;1m%s33[0m' %(sql_l,sql_dic))
107 
108     tag=False  #设置警报 默认是关闭False
109     for item in sql_l:  #循环 按空格切割用户sql的列表
110         if tag and item in sql_dic: #判断警报拉响是True 并且用户sql的条件 在条件select语句字典里面,则关闭警报
111             tag=False #关闭警报
112         if not tag and item in sql_dic: #判断警报没有拉响 并且用户sql的条件 在条件select语句字典里面
113             tag=True #拉响警报
114             key=item #取出用户sql的条件
115             continue #跳出本次判断
116         if tag: #判断报警拉响
117             sql_dic[key].append(item) #把取出的用户sql 添加到 select语句多种条件对应的字典里
118     if sql_dic.get('where'): #判断 用户sql where语句
119         sql_dic['where']=where_parse(sql_dic.get('where')) #['id>4','and','id<10'] #调用where_parse函数 把整理好的用户sql的where语句 覆盖之前没整理好的
120     # print('from in the handle_parse sql_dic is 33[43;1m%s33[0m' %sql_dic)
121     return sql_dic #返回 解析好的 用户sql 字典
122 
123 def where_parse(where_l): #['id>','4','and','id','<10'] ---> #['id>4','and','id<10']
124     '''
125     分析用户sql where的各种条件,再拼成合理的条件字符串
126     :param where_l:用户输入where后对应的过滤条件列表
127     :return:
128     '''
129     res=[]  #存放最后整理好条件的列表
130     key=['and','or','not']  #逻辑运算符
131     char=''  #存放拼接时的字符串
132     for i in where_l:  #循环用户sql
133         if len(i) == 0 :continue  #判断 长度是0 就继续循环
134         if i in key:
135             #i为key当中存放的逻辑运算符
136             if len(char) != 0:  #必须 char的长度大于0
137                 char=three_parse(char)  #把char字符串 转成列表的形式
138                 res.append(char)  #把之前char的字符串,加入res #char='id>4'--->char=['id','>','4']
139                 res.append(i)  #把用户sql 的逻辑运算符 加入res
140                 char=''  #清空 char ,为了下次加入char到res时 数据不重复
141         else:
142             char+=i  #'id>4' #除了逻辑运算符,都加入char #char='id<10'--->char=['id','>','4']
143     else:
144         char = three_parse(char)  # 把char字符串 转成列表的形式
145         res.append(char)  #循环完成后 char里面有数据 ,再加入到res里面
146     # ['id>4','and','id<10'] ---> #['id','>','4','and','id','<','10']
147     # print('from in the where_parse res is 33[43;1m%s33[0m' % res)
148     return res  #返回整理好的 where语句列表
149 
150 def three_parse(exp_str):  # 把where_parse函数里面 char的字符串 转成字典
151     '''
152     将每一个小的过滤条件如,name>=1转换成['name','>=','1']
153     :param exp_str:条件表达式的字符串形式,例如'name>=1'
154     :return:
155     '''
156     key=['>','<','=']  #区分运算符
157     res=[]   #定义空列表 存放最终值
158     char=''  #拼接 值的字符串
159     opt=''   #拼接 运算符
160     tag=False   #定义警报
161     for i in exp_str:  #循环 字符串和运算符
162         if i in key:  #判断 当是运算符时
163             tag=True   #拉响警报
164             if len(char) != 0:  #判断char的长度不等于0时(方便添加连续运算符)才做列表添加
165                 res.append(char)  #把拼接的字符串加入 res列表
166                 char=''   #清空char 使下次循环不重复添加数据到res列表
167             opt+=i    #把循环的运算符加入opt
168         if not tag:   #判断 警报没有拉响
169             char+=i    #把循环的字符串加入 char
170 
171         if tag and i not in key: #判断 警报拉响(表示上次循环到运算符),并且本次循环的不是运算符
172             tag=False  #关闭警报
173             res.append(opt)  #把opt里面的运算符 加入res列表
174             opt=''  #清空opt 使下次循环不重复添加数据到res列表
175             char+=i #把循环到的 字符串加入char
176     else:
177         res.append(char) #循环结束,把最后char的字符串加入res列表
178 
179     #新增解析 like的功能
180     if len(res) == 1:  #判断 ['namelike李'] 是个整体
181         res=res[0].split('like')  #以like切分字符串
182         res.insert(1,'like')  #加入like字符串,因为上面切分的时候剔除了like
183 
184     # print('three_parse res is 33[43;1m%s33[0m' % res)
185     return res  #返回res列表结果
186 
187 #第二部分:sql执行
188 def sql_action(sql_dic): #接收用户输入的sql 的结构化的字典  然后执行sql
189     '''
190     从字典sql_dic提取命令,分发给具体的命令执行函数去执行
191     执行sql的统一接口,内部执行细节对用户完全透明
192     :param sql_dic:
193     :return:
194     '''
195     return sql_dic.get('func')(sql_dic) #接收用户sql,分发sql,执行命令
196 
197 def insert(sql_dic):
198     print('insert %s' %sql_dic)
199     db,table=sql_dic.get('into')[0].split('.')  #切分文件路径,相对应数据库,表
200     with open('%s/%s' %(db,table),'ab+') as fh:  #安装上面的路径 打开文件 ab+模式
201         # 读出文件最后一行,赋值给last 配合+
202         offs = -100  #
203         while True:
204             fh.seek(offs,2)
205             lines = fh.readlines()
206             if len(lines)>1:
207                 last = lines[-1]
208                 break
209             offs *= 2
210         last=last.decode(encoding='utf-8')
211 
212         last_id=int(last.split(',')[0])  #取出最后一行id号
213         new_id=last_id+1   #id号加1 实现id自增效果
214         #insert into db1.emp values alex,30,18500841678,运维,2007-8-1
215         record=sql_dic.get('values')[0].split(',')   #提取用户想要 添加的sql
216         record.insert(0,str(new_id))  #加入自增后的id 到用户sql的头部
217 
218         #['26','alex','35','13910015353','运维','2005 - 06 - 27
']
219         record_str=','.join(record)+'
'  #把用户sql列表切成字符串
220         fh.write(bytes(record_str,encoding='utf-8'))  #把添加 id后的用户想添加的sql  用bytes写入文件
221         fh.flush()
222     return [['insert successful']]
223 
224 def delete(sql_dic):
225     db,table=sql_dic.get('from')[0].split('.')
226     bak_file=table+'_bak'
227     with open("%s/%s" %(db,table),'r',encoding='utf-8') as r_file,
228             open('%s/%s' %(db,bak_file),'w',encoding='utf-8') as w_file:
229         del_count=0
230         for line in r_file:
231             title="id,name,age,phone,dept,enroll_date"
232             dic=dict(zip(title.split(','),line.split(',')))
233             filter_res=logic_action(dic,sql_dic.get('where'))
234             if not filter_res:
235                 w_file.write(line)
236             else:
237                 del_count+=1
238         w_file.flush()
239     os.remove("%s/%s" % (db, table))
240     os.rename("%s/%s" %(db,bak_file),"%s/%s" %(db,table))
241     return [[del_count],['delete successful']]
242 
243 def update(sql_dic):
244     #update db1.emp set id='sb' where name like alex
245     db,table=sql_dic.get('update')[0].split('.')
246     set=sql_dic.get('set')[0].split(',')
247     set_l=[]
248     for i in set:
249         set_l.append(i.split('='))
250     bak_file=table+'_bak'
251     with open("%s/%s" %(db,table),'r',encoding='utf-8') as r_file,
252             open('%s/%s' %(db,bak_file),'w',encoding='utf-8') as w_file:
253         update_count=0
254         for line in r_file:
255             title="id,name,age,phone,dept,enroll_date"
256             dic=dict(zip(title.split(','),line.split(',')))
257             filter_res=logic_action(dic,sql_dic.get('where'))
258             if filter_res:
259                 for i in set_l:
260                     k=i[0]
261                     v=i[-1].strip("'")
262                     print('k v %s %s' %(k,v))
263                     dic[k]=v
264                 print('change dic is %s ' %dic)
265                 line=[]
266                 for i in title.split(','):
267                     line.append(dic[i])
268                 update_count+=1
269                 line=','.join(line)
270             w_file.write(line)
271 
272         w_file.flush()
273     os.remove("%s/%s" % (db, table))
274     os.rename("%s/%s" %(db,bak_file),"%s/%s" %(db,table))
275     return [[update_count],['update successful']]
276 
277 def select(sql_dic):
278     '''
279     执行select语句,接收解析好的sql字典
280     :param sql_dic:
281     :return:
282     '''
283     # print('from select sql_dic is %s' %sql_dic) #打印 解析好的sql字典
284 
285     # first:form
286     db,table=sql_dic.get('from')[0].split('.') #切分出库名和表名,就是文件路径
287 
288     fh=open("%s/%s" %(db,table),'r',encoding='utf-8') #打开文件 根据取到的路径
289 
290     #second:where
291     filter_res=where_action(fh,sql_dic.get('where')) #定义where执行函数,查询条件
292     fh.close()
293     # for record in filter_res:  # 循环打印 用户sql where的执行结果
294     #     print('file res is %s' %record)
295 
296     #third:limit
297     limit_res=limit_action(filter_res,sql_dic.get('limit')) #定义limit执行函数,限制行数
298     # for record in limit_res:  # 循环打印 显示用户sql limit的执行结果
299     #     print('limit res is %s' %record)
300 
301     #lase:select
302     search_res=search_action(limit_res,sql_dic.get('select'))  #定义select执行函数
303     # for record in search_res:  # 循环打印 显示用户sql select的执行结果
304     #     print('select res is %s' %record)
305 
306     return search_res
307 
308 def where_action(fh,where_l):  #执行where条件语句  where_l=where的多条件解析后的列表
309     #id,name,age,phone,dept,enroll_data
310     #10,吴东杭,21,17710890829,运维,1995-08-29
311     #['id>7', 'and', 'id<10', 'or', 'namelike']
312 
313     # print('in where_action 33[41;1m%s33[0m' %where_l)
314     res=[]  #定义最后返回值的列表
315     logic_l=['and','or','not']   #定义逻辑运算符
316     title="id,name,age,phone,dept,enroll_data"  #定义好表文件内容的标题
317     if len(where_l) != 0:  #判断用户sql 是否有where语句
318         for line in fh:  #循环 表文件
319             dic=dict(zip(title.split(','),line.split(','))) #一条记录 让标题和文件内容一一对应
320             #逻辑判断
321             logic_res=logic_action(dic,where_l) #让 logic_action函数来操作对比
322             if logic_res:  #如果逻辑判断为True
323                 res.append(line.split(','))  #加入res
324     else:
325         res=fh.readlines()  #用户sql 没有where语句,则返回表文件所有内容
326 
327     # print('>>>>>>>> %s' %res)
328     return res #返回执行 where 后的结果
329 
330 def logic_action(dic,where_l):
331     '''
332     用户sql select的where多条件 执行对比文件内容
333     文件内容 跟所有的 where_l 的条件比较
334     :param dic:
335     :param where_l:
336     :return:
337     '''
338     # print('from logic_action %s' %dic)  #from logic_action {'id': '23', 'name': '翟超群', 'age': '24', 'phone': '13120378203', 'dept': '运维', 'enroll_data': '2013-3-1
'}
339     # print('---- %s' %where_l)  #[['name', 'like', '李'], 'or', ['id', '<=', '4']]
340     res=[]  #存放 bool值 结果的空列表
341     # where_l=[['name', 'like', '李'], 'or', ['id', '<=', '4']]
342     for exp in where_l:  #循环where条件列表,跟dic做比较
343         #dic与exp做bool运算
344         if type(exp) is list:  #只留下 where_l列表里 相关的条件
345             #如果是列表 做bool运算  #[['name', 'like', '李']
346             exp_k,opt,exp_v=exp  #匹配 一个where条件列表的格式
347             if exp[1]  == '=':   #如果 列表的运算符是 =号
348                 opt="%s=" %exp[1]   #用字符串拼接出 两个 ==号
349             if dic[exp_k].isdigit():  #判断是否数字  用户的条件是否对应文件内容(字典)
350                 dic_v=int(dic[exp_k])  #文件内容的数字 转成整形 做比较
351                 exp_v=int(exp_v)    #where_l列表的数字 转成整形 做比较
352             else:
353                 dic_v="'%s'" %dic[exp_k]  #不是数字的时候 存取出来
354             if opt != 'like':  #如果运算符 不是 like
355                 exp=str(eval("%s%s%s" %(dic_v,opt,exp_v))) #转成字符串(逻辑判断后是bool值):做逻辑判断:文件数字,运算符,用户数字
356             else:   #如果 运算符位置是 like
357                 if exp_v in dic_v:   #判断 sql里like的值 是否在 文件内容里
358                     exp='True'
359                 else:
360                     exp='False'
361         res.append(exp)  #['True','or','False','or','true']
362 
363     # print('---------- %s' %res)
364     res=eval(" ".join(res)) # 把bool值列表转成字符串 然后再做逻辑判断  结果是bool值
365     return res  #返回 res结果
366 
367 def limit_action(filter_res,limit_l): #执行limit条件 限制行数
368     res=[]  #最后的返回值列表
369     if len(limit_l) != 0:  #判断 用户sql 是否有 limit条件
370         index=int(limit_l[0])   #取出 用户sql limit条件的数字
371         res=filter_res[0:index]
372     else:  #如果 用户sql 没有 limit条件 就整个返回
373         res=filter_res
374     return res  #返回最后的sql结果
375 
376 def search_action(limit_res,select_l):  #执行select执行函数
377     res=[]   #最后的返回值列表
378     fileds_l = []
379     title = "id,name,age,phone,dept,enroll_data"   #title = select的条件
380     if select_l[0] == '*' :   #判断 如果 用户sql 的select 条件是 *
381         fields_l=title.split(',')   #用户sql 的select 条件是 * ,则匹配所有条件
382         res=limit_res   #如果 用户sql 的select 条件是 * 则返回全部
383     else:   #判断 如果用户sql的select条件不是 * ,提取用户的select语句条件
384         for record in limit_res:   #循环 匹配好的where语句和limit语句的结果
385             dic=dict(zip(title.split(','),record))   #每条记录都对应 select条件,生成字典
386             r_l=[]   #存放用户sql的select条件
387             fields_l=select_l[0].split(',')  #取出用户sql 的select条件
388             for i in fields_l:   #循环用户sql的select条件,区分多条件,id,name
389                 r_l.append(dic[i].strip())  #把用户sql的select多条件 加入 r_l列表
390             res.append(r_l)   #把r_l列表 加入res
391 
392     return (fields_l,res)  #返回用户sql的select条件,selcet执行结果
393 
394 
395 if __name__ == '__main__':  #程序主函数
396     while True:
397         sql=input("sql> ").strip()  #用户输入sql
398         if sql == 'exit':break      #exit 随时退出
399         if len(sql) == 0 :continue  #用户如果输入空,继续输入
400 
401         sql_dic=sql_parse(sql) #用户输入sql 转成结构化的字典sql_dic
402 
403         #print('main res is %s' %sql_dic) #打印用户非法输入
404         if len(sql_dic) == 0:continue  #如果用户输入等于0 不执行sql_action 让用户继续输入sql
405 
406         res=sql_action(sql_dic) #用户执行sql之后的结果res
407         print('33[43;1m%s33[0m' %res[0])  #打印 select的条件
408         for i in res[-1]:  # 循环打印 显示用户sql select的执行结果
409             print(i)
410 
411 '''
412 测试执行 select语句
413 select * from db1.emp
414 select * from db1.emp limit 3
415 select * from db1.emp where name like 李 or id <= 4 or id = 24 limit 4
416 select id,name from db1.emp where name like 李 or id <= 4 or id = 24 limit 4
417 
418 测试执行 insert语句
419 insert into db1.emp values alex,30,18500841678,运维,2007-8-1
420 
421 测试执行 delete语句
422 delete from db1.emp where id>47
423 
424 测试执行 update语句
425 update db1.emp set alex='haha' where id=47
426 '''
View Code
原文地址:https://www.cnblogs.com/zhuzhiwen/p/7580708.html