I need to built a mini-sql engine in python.So I require a sql-parser for it and I found out about python-sqlparse but am unable to understand how to extract column names or name of the table e.t.c from the SQL query.Can someone help me regarding this matter.
1 Answer
Lets check python sqlparse documentation: Documentation - getting started
You can see there example how parse sql. This is what is there:
1. First you need parse sql statement with parse method:
sql = 'select * from "someschema"."mytable" where id = 1'
parsed = sqlparse.parse(sql)
2. Now you need now get Statement object from parsed:
stmt = parsed[0]
'''(<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>)'''
3. then you can read again parsed sql statement with str() method:
#all sql statement
str(stmt)
#only parts of sql statements
str(stmt.tokens[-1])
#so the result of last str() method is 'where id = 1'
Result of str(stmt.tokens[-1]) is then 'where id = 1'
If you want name of the table you just need write:
str(stmt.tokens[-3])
#result "someschema"."mytable"
If you need names of the columns you can call:
str(stmt.tokens[2])
#result *, now it is operator * because there are not columns in this sql statements
4 Comments
Chaitu. Petluri
Thanks I got it :)
ahmadalibaloch
sqlparse.parse(sql)[0].get_name() gives table nameSrishti
I am trying to perform operation on CREATE statement, how can i find the name of all columns, i tried using str(stmt.tokens[2]) but it doesn't gives the column name.
Abhinandan Dubey
Just trying to understand how is this better than string.split() ?