2013-01-24 40 views
9

我們需要用於Python的SQL解析或分解庫。我們希望能夠輸入一個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 

誰能給我們這方面的任何指針?如果功能更有限,那也可以。

非常感謝!

+2

http://stackoverflow.com/questions/1394998/parsing-sql-with-python和HTTP ://navarra.ca/?p = 538 –

+2

的確,我打算建議使用pyparsing,但上面的鏈接問題已經做到了。 –

回答

6

你可能想看看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>) 
>>> 
+1

正是我們需要的。謝謝! –