我能够通过对简单的选择 SQL 使用 sql 解析来获取列名和表名。
有人可以帮助如何从任何复杂的 SQL 中获取列名和表名。
最佳答案
这是一个从复杂的sql select 语句中提取列名的解决方案。 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']
关于python-3.x - 如何在 python3 中使用 SQL 解析器解析任何 SQL 获取列名和表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60822203/