Parsing SQL queries in python
<p>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.</p>

<p>Lets check python sqlparse documentation: <a href="https://sqlparse.readthedocs.io/en/latest/intro/#getting-started" rel="nofollow">Documentation - getting started</a></p>

<p>You can see there example how parse sql. This is what is there:</p>

<p><strong>1. First you need parse sql statement with parse method:</strong></p>

<pre><code>sql = 'select * from "someschema"."mytable" where id = 1'
parsed = sqlparse.parse(sql)
</code></pre>

<p><strong>2. Now you need now get Statement object from parsed:</strong></p>

<pre><code>stmt = parsed[0]
    '''(&lt;DML 'select' at 0x9b63c34&gt;,
 &lt;Whitespace ' ' at 0x9b63e8c&gt;,
 &lt;Operator '*' at 0x9b63e64&gt;,
 &lt;Whitespace ' ' at 0x9b63c5c&gt;,
 &lt;Keyword 'from' at 0x9b63c84&gt;,
 &lt;Whitespace ' ' at 0x9b63cd4&gt;,
 &lt;Identifier '"somes...' at 0x9b5c62c&gt;,
 &lt;Whitespace ' ' at 0x9b63f04&gt;,
 &lt;Where 'where ...' at 0x9b5caac&gt;)'''
</code></pre>

<p><strong>3. then you can read again parsed sql statement with str() method:</strong></p>

<pre><code>#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'
</code></pre>

<p>Result of <code>str(stmt.tokens[-1])</code> is then <code>'where id = 1'</code></p>

<p><strong>If you want name of the table you just need write:</strong></p>

<pre><code>str(stmt.tokens[-3])
#result "someschema"."mytable"
</code></pre>

<p><strong>If you need names of the columns you can call:</strong></p>

<pre><code>str(stmt.tokens[2])
#result *, now it is operator * because there are not columns in this sql statements
</code></pre>

python sql parsing