python-3.x - 如何在 python3 中使用 SQL 解析器解析任何 SQL 获取列名和表名

标签 python-3.x sql-parser

我能够通过对简单的选择 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/

相关文章:

python - 如何使用 numba 创建给定类型的 numpy 数组

python - 使用 Python 连接到 MS Access

php - ReplaceProcessor::process($tokenList) 的声明必须与 InsertProcessor::process($tokenList, $token_category = 'INSERT' ) 兼容

python - 读取各种不同编码的文件

python - Flask 单击按钮即可转到新页面

python-3.x - Flask 中的线程不能与 UWSGI 一起使用,但可以在命令行上工作

java - 在jsqlparser中向sql查询添加语句

Python解析SQL并查找关系

java - JSqlParser 如何拆分一个表达式