Python的SQL解析库

12 投票
1 回答
10502 浏览
提问于 2025-04-17 13:35

我们需要一个可以解析或分解SQL语句的库,最好是用Python来做。我们想要输入一段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

有没有人能给我们一些建议呢?如果功能比较简单也没关系。

非常感谢!

1 个回答

9

你可以看看这个叫做 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>)
>>>

撰写回答