3

I need to extract parameters like table names, selected columns and WHERE-statements for a given SQL string in Python 3. Is there a a library, that can do this and could I get an example for my case? Something like:

sql = 'select cola, colb, colc from "someschema"."mytable" where id = 1'
result = sqlparse(sql)
print(result.columns)
>> ["cola","colb","colc"]

print(result.tables)
>> ["mytable"]

If the question is not clear: The same question was asked before for C# extract column names and table name from any "SQL query" String

Mehmet Ates
  • 135
  • 1
  • 2
  • 11

1 Answers1

3

You can use sqlparser

The example with table names extraction is here: https://github.com/andialbrecht/sqlparse/blob/master/examples/extract_table_names.py

The example with columns extraction is here: https://github.com/andialbrecht/sqlparse/blob/master/examples/column_defs_lowlevel.py

Ivan Sudos
  • 1,423
  • 2
  • 13
  • 25