python-3.x - 如何在python3中使用SQL解析器解析任何SQL获取列名和表名
问题描述
我能够通过使用 sql 解析来获取列名和表名,仅用于简单的选择 SQL。
有人可以帮助如何从任何复杂的 SQL 中获取列名和表名。
解决方案
Here is a solution for extracting column names from complex sql select statements. Python 3.9
import sqlparse
def get_query_columns(sql):
stmt = sqlparse.parse(sql)[0]
columns = []
column_identifiers = []
# get column_identifieres
in_select = False
for token in stmt.tokens:
if isinstance(token, sqlparse.sql.Comment):
continue
if str(token).lower() == 'select':
in_select = True
elif in_select and token.ttype is None:
for identifier in token.get_identifiers():
column_identifiers.append(identifier)
break
# get column names
for column_identifier in column_identifiers:
columns.append(column_identifier.get_name())
return columns
def test():
sql = '''
select
a.a,
replace(coalesce(a.b, 'x'), 'x', 'y') as jim,
a.bla as sally -- some comment
from
table_a as a
where
c > 20
'''
print(get_query_columns(sql))
test()
# outputs: ['a', 'jim', 'sally']
推荐阅读
- java - 将java项目转换为maven时pom文件出错
- php - Magento vs Opencart vs WooCommerce for AutoParts
- html - HTML 类语法
- c# - 以前的用户登录被最近/最新的用户登录替换
- java - 为什么 PDF InputStream.read() 返回 -1?
- vue.js - 自动将新帖子添加到侧边栏
- git - 如何对他人的拉取请求执行拉取请求
- python - 使用 matplotlib 从 CSV 创建绘图失败
- javascript - 在这种情况下,我是否需要在 angularjs 中手动管理范围?
- prolog - SWI-prolog - 如何使用键盘快捷键或全局谓词清除终端屏幕?