Python的SQL解析库

2024-04-29 19:21:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我们需要一个用于Python的SQL解析或分解库。我们希望能够输入一个SQL文本查询,然后作为结果返回查询部分。它不需要花哨,或者其他什么,但是我们喜欢避免自己做解析。理想情况下,我们可以这样做:

the_query = "select something from some_table where blah = 'thing' limit 15"
query_parts = the_library.parse(the_query)
print query_parts.limit().val()

>>> '15'

还有这个:

the_query = "select something from some_table where blah = 'thing'"
query_parts = the_library.parse(the_query)
print query_parts.limit().val()

>>> None

有人能给我们指点一下吗?如果功能比较有限,也可以。

非常感谢!


Tags: thefromsqlparselibrarytablesomewhere
1条回答
网友
1楼 · 发布于 2024-04-29 19:21:31

你可能想看看sqlparse

从他们的主页上公然盗取:

>>> # Parsing
>>> res = sqlparse.parse('select * from "someschema"."mytable" where id = 1')
>>> res
<<< (<Statement 'select...' at 0x9ad08ec>,)
>>> stmt = res[0]
>>> stmt.to_unicode()  # converting it back to unicode
<<< u'select * from "someschema"."mytable" where id = 1'
>>> # This is how the internal representation looks like:
>>> stmt.tokens
<<<
(<DML 'select' at 0x9b63c34>,
 <Whitespace ' ' at 0x9b63e8c>,
 <Operator '*' at 0x9b63e64>,
 <Whitespace ' ' at 0x9b63c5c>,
 <Keyword 'from' at 0x9b63c84>,
 <Whitespace ' ' at 0x9b63cd4>,
 <Identifier '"somes...' at 0x9b5c62c>,
 <Whitespace ' ' at 0x9b63f04>,
 <Where 'where ...' at 0x9b5caac>)
>>>

相关问题 更多 >