Python写的模拟sql查询的练手小程序

需求如下

可进行模糊查询,语法至少支持下面3种:
  select name,age from staff_table where age > 22
  select * from staff_table where dept = "IT"
select * from staff_table where enroll_date like "2013"
查到的信息,打印后,最后面还要显示查到的条数

查到的信息,打印后,最后面还要显示查到的条数
可创建新员工纪录,以phone做唯一键,staff_id需自增
可删除指定员工信息纪录,输入员工id,即可删除
可修改员工信息,语法如下:
  UPDATE staff_table SET dept="Market" where dept = "IT"
  1 #!/usr/bin/env python
  2 #-*- coding:utf-8 -*-
  3 # @Time    : 2017/9/22 14:30
  4 # @Author  : lichuan
  5 # @File    : lianxi.py
  6 
  7 
  8 
  9 import  os
 10 
 11 def where(sql):
 12     # sql='age > 22'
 13     lines=''
 14     s=sql.split()
 15     index=title.index(str(s[0]).strip())
 16     with open('info.txt',encoding='utf-8') as read_f:
 17         for line in read_f:
 18             l=line.split(',')
 19             # print(str(l[index]))
 20             # print(str(s[-1]).strip().strip('"').strip("'"))
 21             if 'like' in sql and str(s[-1]).strip('"').strip("'") in str(l[index]):
 22                 lines=lines+line
 23             elif '>' in sql and str(s[-1]).strip("'").strip('"').isdigit() and int(l[index]) > int(str(s[-1]).strip("'").strip('"')):
 24                 lines = lines + line
 25             elif '<' in sql and s[-1].isdigit() and int(l[index]) < int(s[-1]):
 26                 lines = lines + line
 27             elif '=' in sql and  str(l[index]) == str(s[-1]).strip().strip('"').strip("'"):
 28                 lines = lines + line
 29             # print("str(l[index]).upper() is %s" %str(l[index]).upper())
 30             # print("str(s[-1]) is %s" %str(s[-1]))
 31         return lines
 32 
 33 
 34 def tablename_check(fun):
 35     def wrapper(sql):
 36         # sql=''
 37         check=sql.split()
 38         # print(check)
 39         # print('staff_table' in check)
 40         if 'staff_table' in check:
 41             fun(sql)
 42         else:
 43             print("staff_tab is needed!")
 44             return 1
 45     return wrapper
 46 
 47 
 48 def from_check(fun):
 49     def inner_check(sql):
 50         s=sql.lower().split()
 51         if "from" not in s:
 52             print("no from in the sql!")
 53             return 1
 54         for item in s:
 55             if item == "from":
 56                 i=s.index("from")+1
 57                 if s[i] == "staff_table":
 58                     fun(sql)
 59                 else:
 60                     print("table name is wrong! table name is staff_table")
 61     return inner_check
 62 
 63 def where_check(fun):
 64     def inner_check(sql):
 65         s1=str(sql.lower().split('where')[1]).split()
 66         if len(s1) != 3:
 67             print("%s is wrong" % str(s1))
 68             return 1
 69         s=sql.lower()
 70         if "where" not in s:
 71             print("no where in the sql!")
 72             fun(sql)
 73         else:
 74             i=str(s.split('where')[1]).split()[0]
 75             i=str(i).strip()
 76             if i in title :
 77                 fun(sql)
 78             else:
 79                 print("where %s is wrong! " %str(i))
 80     return inner_check
 81 
 82     # with open("info.txt",encoding='utf-8') as read_f:
 83     #     for line in read_f:
 84     #         d=line.split(",")
 85 
 86 def insert_check(fun):
 87     def inner_check(sql):
 88         # sql="insert into staff_table (name,age,phone,dept,enroll_date) values ('lit','18','13523081939','IT','2009-03-01')"
 89         # s=''
 90         sl=sql.split()
 91         if 'values' not in sl and 'values'.upper() not in sl:
 92             print("values in needed")
 93             return 1
 94         if "insert into staff_table" not in sql and "insert into staff_table".upper() not in sql:
 95             print("no insert into staff_table in the sql!")
 96             return 1
 97         else:
 98             keys=str(sql.split(')')[0].split('(')[1]).split(',')
 99             for k in title:
100                 if k not in keys and k != 'staff_id':
101                     print("%s is not defined" %k)
102                     return 1
103             fun(sql)
104     return inner_check
105 
106 @where_check
107 @from_check
108 def select(sql):
109     ''' select staff_id,name,age,phone,dept,enroll_date from staff_table where name = "Alex"'''
110     # str1=''
111     # sql=''
112     sql=sql.replace(';','')
113     i=sql.find("from")
114     list=sql[7:i].strip().split(",")
115     # print(list)
116     s=set(list)
117     count=0
118     lines=''
119     if list[0] == '*':
120         if 'where' in sql:
121             wh=sql.split('where')
122             lines=where(wh[1])
123             # print(lines)
124         else:
125             with open('info.txt',encoding='utf-8') as read_f:
126                 for line in read_f:
127                     lines=lines+line
128         # print(lines)
129         for line in lines.split('\n'):
130             if line != '':
131                 print(line)
132                 # print('**********************************')
133                 count+=1
134         print("\n%d 行被选择" %count)
135     elif s.issubset(set(title)):
136         if 'where' in sql.lower():
137             wh=sql.split('where')
138             lines=where(wh[1])
139             # print(lines)
140         else:
141             with open('info.txt',encoding='utf-8') as read_f:
142                 for line in read_f:
143                     lines=lines+line
144         # print(lines)
145         for line in lines.split('\n'):
146             if line != '':
147                 new_line=''
148                 l=line.split(',')
149                 sub=sql_list[1].split(',')
150                 # print('sub is '+str(sub))
151                 for sl in sub:
152                     i=title.index(sl)
153                     # print('i is '+str(i))
154                     new_line+=str(l[i])+','
155                 print(new_line.strip(','))
156                 # print('**********************************')
157                 count+=1
158         print("\n%d 行被选择" %count)
159     else:
160         print(','.join(list)+" is wrong")
161     return sql
162 
163 @tablename_check
164 @where_check
165 def update(sql):
166     '''
167     UPDATE staff_table SET dept="Market" where dept = "IT"
168     '''
169     s=sql.split()
170 
171     if 'where' not in s and 'WHERE' not in s:
172         print("no where in the sql,try again")
173         return 1
174     if 'SET' not in s and 'set' not in s:
175         print("no set in the sql,try again")
176         return 1
177 
178     s1 = sql.split('where')[1]
179     # print("s1"+s1)
180     wh=where(str(s1))
181     # print('wh'+wh)
182     lines=''
183     value=str(str(sql.split('where')[0]).split('=')[1]).strip().strip('"').strip("'")
184     with open('info.txt','r',encoding='utf-8') as read_f, open('info.txt.swap','w',encoding='utf-8') as write_f:
185         for f in read_f:
186             if f not in wh:
187                 lines=lines+f
188             else:
189                 for i in title:
190                     # print(i)
191                     if i in sql.lower():
192                         old=f.split(',')[title.index(i)]
193                         # print("old"+old)
194                         f=f.replace(old,value)
195                 lines=lines+f
196         # print(lines)
197         write_f.write(lines.strip('\n'))
198         read_f.close()
199         write_f.close()
200         os.remove('info.txt')
201         os.rename('info.txt.swap', 'info.txt')
202 
203 
204 @tablename_check
205 @insert_check
206 def insert(sql):
207     keys=sql.split(')')[0].split('(')[1].split(',')
208     # print(keys)
209     values=sql.split('(')[2].split(')')[0].split(',')
210     # print(values)
211     line = ''
212     if sql.split()[2] != 'staff_table':
213         print('table name is wrong,the right name is staff_table')
214     elif sql.split():
215         with open('info.txt','r+',encoding='utf-8') as read_f:
216             r=read_f.readlines()
217             staff_id=int(r[-1].split(',')[0])+1
218             name=values[keys.index('name')].replace("'",'')
219             age=values[keys.index('age')].replace("'",'')
220             phone=values[keys.index('phone')].replace("'",'')
221             dept=values[keys.index('dept')].replace("'",'')
222             enroll_date=values[keys.index('enroll_date')].replace("'",'')
223             line="\n%d,%s,%s,%s,%s,%s" %(staff_id,name,age,phone,dept,enroll_date)
224             l=[i for i in r if str(phone)==str(i.split(',')[3])]
225             # print(l)
226             if  l:
227                 print('%s is already in use.' % phone)
228             else:
229                 read_f.write(line)
230 
231 
232 @where_check
233 @from_check
234 @tablename_check
235 def delete(sql):
236     # sql='delete from staff_table where id=王伟'
237     # print(sql)
238     if 'where' not in sql and 'WHERE' not in sql:
239         print("no where in the sql,try again")
240         return 1
241     s=str(sql.split('where')[1])
242     wh=where(s)
243     print(wh)
244     lines=''
245     with open('info.txt','r',encoding='utf-8') as read_f,open('info.txt.swap','w',encoding='utf-8') as write_f:
246         # l=str(read_f.readlines()).replace('wh','')
247         # write_f.write(l)
248         for f in read_f:
249             if f not in wh:
250                 lines=lines+f
251         # print(lines)
252         write_f.write(lines.strip('\n'))
253         read_f.close()
254         write_f.close()
255         os.remove('info.txt')
256         os.rename('info.txt.swap','info.txt')
257 
258 
259 
260 title=['staff_id','name','age','phone','dept','enroll_date']
261 
262 func={
263     "select":select,
264     "update":update,
265     "insert":insert,
266     "delete":delete
267 }
268 
269 
270 while True:
271     sql = input("q==quit;input your sql:").strip()
272     if sql.strip().lower() == 'q':
273         break
274     sql_list = sql.split()
275     # print(sql_list)
276     if sql_list[0].lower() in func:
277         func[str(sql_list[0]).lower()](sql)
278     else:
279         print("wrong,please input your sql again!")
原文地址:https://www.cnblogs.com/litzhiai/p/7644883.html