i need built mini-sql engine in python.so require sql-parser , found out python-sqlparse unable understand how extract column names or name of table e.t.c sql query.can me regarding matter.
lets check python sqlparse documentation: documentation - getting started
you can see there example how parse sql. there:
1. first need parse sql statement parse method:
sql = 'select * "someschema"."mytable" id = 1' parsed = sqlparse.parse(sql)
2. need statement object parsed:
stmt = parsed[0] '''(<dml 'select' @ 0x9b63c34>, <whitespace ' ' @ 0x9b63e8c>, <operator '*' @ 0x9b63e64>, <whitespace ' ' @ 0x9b63c5c>, <keyword 'from' @ 0x9b63c84>, <whitespace ' ' @ 0x9b63cd4>, <identifier '"somes...' @ 0x9b5c62c>, <whitespace ' ' @ 0x9b63f04>, <where 'where ...' @ 0x9b5caac>)'''
3. can read again parsed sql statement str() method:
#all sql statement str(stmt) #only parts of sql statements str(stmt.tokens[-1]) #so result of last str() method 'where id = 1'
result of str(stmt.tokens[-1])
'where id = 1'
if want name of table need write:
str(stmt.tokens[-3]) #result "someschema"."mytable"
if need names of columns can call:
str(stmt.tokens[2]) #result *, operator * because there not columns in sql statements
Comments
Post a Comment