2013-01-24 23 views
9

için biz Python için bir SQL ayrıştırma veya çürüyen kitaplık gerekir. Biz giriş SQL metin sorgusu edebilmek ve sonra geri sonucunda sorgu parçalarını almak istiyorum. Fantezi ya da bir şey olmak zorunda değildir, ama biz kendimizi ayrıştırma yaparak önlemek ister ediyorum . deSQL Ayrıştırma kütüphanesi Python

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' 

Ve bu: İdeal olarak, böyle bir şey yapabileceğini

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

>>> None 

kimse bize bunun için herhangi bir işaretçiler verebilir misiniz? işlevselliği daha sınırlıdır, bu yanı tamam.

Çok teşekkürler!

+2

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

+2

Gerçekten de, pyparsing kullanmayı önerecektim, ancak yukarıdaki bağlantılı soru zaten bunu yapıyor. biz gerekli Tam olarak ne –

cevap

6

Sen Açıkça kendi ana çalınan sqlparse

bakmak isteyebilirsiniz:

>>> # 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

. Teşekkürler! –