python处理sql文件_Python 操作文件模拟SQL语句功能

1 #/usr/local/env python

2 #_*_coding:utf-8_*_

3

4 #第一部分:sql解析

5 importos6 def sql_parse(sql): #用户输入sql 转成结构化的字典

7 '''

8 第一步:sql解析 流程9 1.收到 sql查询条件10 2.sql_parse 来分发要求给 select_parse11 3.select_parse 调用 handle_parse 解析sql12 4.handle_parse 返回解析sql后的结果 sql_dic 给 select_parse13 5.select_parse 把 sql_dic 返回给sql_parse14 sql_dic=sql_parse(sql) #用户输入sql 转成结构化的字典sql_dic15 sql语句四种操作格式:insert delete update select16 提取用户输入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 inparse_func:36 res=parse_func[func](sql_l) #把切割后的 用户sql的列表 传入对应的sql命令函数里

37

38 returnres39

40 definsert_parse(sql_l):41 '''

42 定义insert语句的语法结构,执行sql解析操作,返回sql_dic43 :param sql:sql按照空格分割的列表44 :return:返回字典格式的sql解析结果45 '''

46 sql_dic={47 'func':insert, #函数名

48 'insert':[], #insert选项,留出扩展

49 'into':[], #表名

50 'values':[], #值

51 }52 returnhandle_parse(sql_l,sql_dic)53

54 defdelete_parse(sql_l):55 '''

56 定义delete语句的语法结构,执行sql解析操作,返回sql_dic57 :param sql:sql按照空格分割的列表58 :return:返回字典格式的sql解析结果59 '''

60 sql_dic ={61 'func': delete,62 'delete': [], #delete选项,留出扩展

63 'from': [], #表名

64 'where': [], #filter条件

65 }66 returnhandle_parse(sql_l, sql_dic)67

68 defupdate_parse(sql_l):69 '''

70 定义update语句的语法结构,执行sql解析操作,返回sql_dic71 :param sql:sql按照空格分割的列表72 :return:返回字典格式的sql解析结果73 '''

74 sql_dic ={75 'func': update,76 'update': [], #update选项,留出扩展

77 'set': [], #修改的值

78 'where': [], #filter条件

79 }80 returnhandle_parse(sql_l, sql_dic)81

82 defselect_parse(sql_l):83 '''

84 定义select语句的语法结构,执行sql解析操作,返回sql_dic85 :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 returnhandle_parse(sql_l,sql_dic)98

99 def handle_parse(sql_l,sql_dic): #专门做sql解析操作

100 '''

101 执行sql解析操作,返回sql_dic102 :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 inkey: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','

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 definsert(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 whileTrue: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 defdelete(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=0230 for line inr_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 notfilter_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 defupdate(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 inset: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=0254 for line inr_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 iffilter_res:259 for i inset_l:260 k=i[0]261 v=i[-1].strip("'")262 print('k v %s %s' %(k,v))263 dic[k]=v264 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 defselect(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 returnsearch_res307

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 deflogic_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_res374 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 whileTrue: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.emp414 select * from db1.emp limit 3415 select * from db1.emp where name like 李 or id <= 4 or id = 24 limit 4416 select id,name from db1.emp where name like 李 or id <= 4 or id = 24 limit 4417

418 测试执行 insert语句419 insert into db1.emp values alex,30,18500841678,运维,2007-8-1420

421 测试执行 delete语句422 delete from db1.emp where id>47423

424 测试执行 update语句425 update db1.emp set alex='haha' where id=47426 '''

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个用PythonSQL实现的文件处理平台实践程序的简单示例。 首先,您需要安装PythonSQL数据库,如MySQL、PostgreSQL等。然后,您需要使用Python的第三方库来处理文件,如pandas、numpy等。 接下来,您需要编写Python代码来读取文件,并将文件数据存储到数据库中。以下是一个简单的示例代码: ```python import pandas as pd import sqlite3 # 读取文件 df = pd.read_csv('file.csv') # 连接数据库 conn = sqlite3.connect('data.db') # 将数据存储到数据库中 df.to_sql('data', conn, if_exists='replace') ``` 以上代码将读取名为file.csv的文件,并将数据存储到名为data.db的SQLite数据库中。 接下来,您需要编写SQL查询语句来查询数据库中的数据。以下是一个简单的示例代码: ```python import sqlite3 # 连接数据库 conn = sqlite3.connect('data.db') # 查询数据 cursor = conn.execute('SELECT * FROM data') for row in cursor: print(row) ``` 以上代码将查询数据库中的所有数据,并将其打印出来。 最后,您需要编写代码来处理错误,并生成文件处理信息。以下是一个简单的示例代码: ```python import pandas as pd import sqlite3 import logging # 设置日志记录器 logger = logging.getLogger(__name__) # 读取文件 try: df = pd.read_csv('file.csv') except Exception as e: logger.error('读取文件失败: %s', str(e)) # 连接数据库 try: conn = sqlite3.connect('data.db') except Exception as e: logger.error('连接数据库失败: %s', str(e)) # 将数据存储到数据库中 try: df.to_sql('data', conn, if_exists='replace') except Exception as e: logger.error('存储数据失败: %s', str(e)) # 查询数据 try: cursor = conn.execute('SELECT * FROM data') for row in cursor: print(row) except Exception as e: logger.error('查询数据失败: %s', str(e)) ``` 以上代码将使用Python的日志记录器来记录错误,并在发生错误时打印错误信息。 总之,以上是一个简单的用PythonSQL实现的文件处理平台实践程序的示例。您可以根据自己的需求进行修改和扩展。希望对您有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值