我能够通过使用sql解析获得列名和表名,只对简单的select SQL进行解析。
有人能帮我吗?如何从任何复杂的SQL中获取列名和表名?
发布于 2020-03-27 20:36:24
这就是在sqlparse中打印表名的方式
1)使用SELECT语句
>>> import sqlparse
>>> print([str(t) for t in parse[0].tokens if t.ttype is None][0])
'dbo.table'
(或)
2)使用INSERT语句:
def extract_tables(sql):
"""Extract the table names from an SQL statment.
Returns a list of (schema, table, alias) tuples
"""
parsed = sqlparse.parse(sql)
if not parsed:
return []
# INSERT statements must stop looking for tables at the sign of first
# Punctuation. eg: INSERT INTO abc (col1, col2) VALUES (1, 2)
# abc is the table name, but if we don't stop at the first lparen, then
# we'll identify abc, col1 and col2 as table names.
insert_stmt = parsed[0].token_first().value.lower() == "insert"
stream = extract_from_part(parsed[0], stop_at_punctuation=insert_stmt)
return list(extract_table_identifiers(stream))
列名可能很棘手,因为列名可能是不明确的,甚至是派生的。但是,您几乎可以从任何查询或存储过程中获取列名、序列和类型。
在遇到FROM关键字之前,将获取所有列名。
def parse_sql_columns(sql):
columns = []
parsed = sqlparse.parse(sql)
stmt = parsed[0]
for token in stmt.tokens:
if isinstance(token, IdentifierList):
for identifier in token.get_identifiers():
columns.append(str(identifier))
if isinstance(token, Identifier):
columns.append(str(token))
if token.ttype is Keyword: # from
break
return columns
https://stackoverflow.com/questions/60822203
复制相似问题