首页 > 解决方案 > 如何在python3中使用SQL解析器解析任何SQL获取列名和表名

问题描述

我能够通过使用 sql 解析来获取列名和表名,仅用于简单的选择 SQL。

有人可以帮助如何从任何复杂的 SQL 中获取列名和表名。

标签: python-3.xsql-parser

解决方案


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']

推荐阅读