如何使用sqlparser将SQL查询和子查询解析为python

时间:2014-03-10 15:04:50

标签: python-2.7

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

e.g:

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子查询。

2 个答案:

答案 0 :(得分:2)

不太优雅,但有效:

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)

答案 1 :(得分:-1)

该库可以解析并生成SQL https://code.google.com/p/python-sql/