0

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
  • without a specific problem, no one can help you here. Commented Sep 2, 2016 at 10:19

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks I got it :)
sqlparse.parse(sql)[0].get_name() gives table name
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.
Just trying to understand how is this better than string.split() ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.