gpt4 book ai didi

python-2.7 - 如何使用sqlparser将SQL查询和子查询解析成python

转载 作者:行者123 更新时间:2023-12-02 03:37:48 28 4
gpt4 key购买 nike

想解析sql join查询,选择子查询进入python。我正在使用 sqlparse 库。但我无法解析子查询。我如何解析整个查询。

例如:

query = "select id,fname,lname,address from res_users as r left join res_partner as p on p.id=r.partner_id where name = (select name from res_partner where id = 1)"

query_tokens = sqlparse.parse(query)[0].tokens

我无法解析这个 select name from res_partner where id = 1子查询。

最佳答案

不那么优雅,但有效:

import sqlparse
from sqlparse.sql import Where, Comparison, Parenthesis

query = """
select
id,fname,lname,address
from
res_users as r
left join
res_partner as p
on
p.id=r.partner_id
where
name = (select name from res_partner where id = 1)"""

query_tokens = sqlparse.parse(query)[0]
where = next(token for token in query_tokens.tokens if isinstance(token, Where))
condition = next(token for token in where.tokens if isinstance(token, Comparison))
subquery = next(token for token in condition.tokens if isinstance(token, Parenthesis))
print subquery

打印:
(select name from res_partner where id = 1)

关于python-2.7 - 如何使用sqlparser将SQL查询和子查询解析成python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22303812/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com