本篇文章介绍了Python使用ply和re模块提取sql语句中表名的方法,具有一定的参考价值,希望对各位学习Python的朋友有帮助!
	![图片[1]-Python怎么从sql提取表名-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/5e7dccfb8e4e3864.jpg)
Python怎么从sql提取表名
ply:词法语法解析模块;
re:正则表达式模块。
全部代码如下:
importply.lexaslex,re
defextract_table_name_from_sql(sql_str):
#removethe/**/comments
q=re.sub(r"/\*[^*]*\*+(?:[^*/][^*]*\*+)*/","",sql_str)
#removewholeline--and#comments
lines=[lineforlineinq.splitlines()ifnotre.match("^\s*(--|#)",line)]
#removetrailing--and#comments
q="".join([re.split("--|#",line)[0]forlineinlines])
#splitonblanks,parensandsemicolons
tokens=re.split(r"[\s)(;]+",q)
#scanthetokens.ifweseeaFROMorJOIN,wesettheget_next
#flag,andgrabthenextone(unlessit'sSELECT).
result=[]
get_next=False
fortokenintokens:
ifget_next:
iftoken.lower()notin["","select"]:
result.append(token)
get_next=False
get_next=token.lower()in["from","join"]
returnresult
sql2="SELECTa.time_updated_server/1000,content,nick,nameFROM"\
"table1aJOIN"\
"table2bONa.sender_id=b.user_idJOINtable3cONa.channel_id=c.channel_idJOINtable4dONc.store_id=d.store_idWHEREsender_idNOTIN(SELECTuser_idFROMtable5WHEREstore_idIN('agent_store:1','ask:1'))ANDto_timestamp(a.time_updated_server/1000)::date>='2014-05-01'GROUPBY1,2,3,4HAVINGsum(1)>500ORDERBY1ASC"
print(extract_table_name_from_sql(sql2))原文来自:https://www.py.cn                    © 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
    


















































 
        

暂无评论内容