viblo
viblo

Reputation: 4603

Highlight of SQL inside python strings

I use jupyter notebook with python to do database queries using the db.py library.

For example, it might look like (inside my code cell):

df = db.query(""" 
SELECT a,b 
  FROM c 
  ORDER BY d DESC
""")

What I would like to have is syntax highlighting of the SQL inside my string. Is that possible? A suggestion on how to build it would also help!

Upvotes: 13

Views: 2885

Answers (1)

krvkir
krvkir

Reputation: 821

It seems that the closest thing to what you want is IPython-SQL plugin (https://github.com/catherinedevlin/ipython-sql). It enables %sql and %%sql magic so that you can write sql code without strings, assign the result to some variable and then make a dataframe from this result.

>>> %sql postgresql:///master
'Connected: None@master'
>>> res = %sql SELECT * FROM some_table
731 rows affected.
>>> df = res.DataFrame()
>>> type(df)
pandas.core.frame.DataFrame

And since sql query is written not inside the string, you get some highlighting (actually it's misused highlighting for python code, but it makes things a little prettier).

Upvotes: 1

Related Questions