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 :\033[42;1m%s\033[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 \033[41;1m%s\033[0m \nsql_dic is \033[41;1m%s\033[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 \033[43;1m%s\033[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 \033[43;1m%s\033[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 \033[43;1m%s\033[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\n']
219         record_str=','.join(record)+'\n'  #把用戶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 \033[41;1m%s\033[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\n'}
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('\033[43;1m%s\033[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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM