Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 813
viblo Avatar asked Dec 17 '15 10:12

viblo


People also ask

How do I enable syntax highlighting in Python?

You can change the syntax highlighting theme by clicking Options > Configure IDLE and switching to the Highlights tab.

How do you create a multiline query in Python?

You can have a string split across multiple lines by enclosing it in triple quotes. Alternatively, brackets can also be used to spread a string into different lines. Moreover, backslash works as a line continuation character in Python. You can use it to join text on separate lines and create a multiline string.


1 Answers

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).

like image 176
krvkir Avatar answered Sep 22 '22 06:09

krvkir