我正在尝试从给定的 SQL 查询(从 MySQL 开始)中提取所有列名。我在 python 中使用 sqlparser 模块。
我有一个简单的代码来获取列,直到达到“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
示例查询:
string2 = "SELECT test, ru.iuserid AS passengerid, ru.vimgname FROM ratings_user_driver AS rate LEFT JOIN trips AS tr ON tr.itripid = rate.itripid LEFT JOIN register_user AS ru ON ru.iuserid = tr.iuserid WHERE tr.idriverid='5083' AND tr.iactive='Finished' AND tr.ehailtrip='No' AND rate.eusertype='Passenger' ORDER BY tr.itripid DESC LIMIT 0,10;"
预期输出:
["test", "ru.iuserid AS passengerid", "ru.vimgname", "tr.itripid", "rate.itripid","ru.iuserid", "tr.iuserid","tr.idriverid", "tr.iactive", "tr.ehailtrip", "rate.eusertype", "tr.itripid"]
我面临的另一个问题是“这个解析器没有正确处理 where 子句。它没有被识别为关键字,因此,我无法清楚地从中提取信息