How do I split thE sql
string x
, in the following snippet, onto several lines - this is in a Jupyter
notebook?
import pandas as pd
import pyodbc as p
def s(sqlString):
cnxn = p.connect(driver='{SQL Server}', server='SERVERNAME', database='OURDBNAME', uid='myLOGIN', pwd='myPWD')
df = pd.read_sql(sqlString, cnxn)
return df
x = "SELECT * FROM OURDBNAME.dbo.vw_DimFoo"
df = s(x)
(Ideally I'd like to not have to deal with lots of concatenation ...not sure if this is possible)
Use a backslash ( \ ) as a line continuation character If a backslash is placed at the end of a line, it is considered that the line is continued on the next line. Only string literals (string surrounded by ' or " ) are concatenated if written consecutively. Note that in the case of variables, an error is raised.
Use triple quotes to create a multiline string It is the simplest method to let a long string split into different lines. You will need to enclose it with a pair of Triple quotes, one at the start and second in the end. Anything inside the enclosing Triple quotes will become part of one multiline string.
What does %% capture do in Jupyter? Capturing Output With %%capture IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable. By default, %%capture discards these streams. This is a simple way to suppress unwanted output.
Use Python's triple quote notation to define a multi-line string:
x = """\
Select *
FROM OURDBNAME.dbo.vw_DimFoo
"""
print(x)
results in
Select *
FROM OURDBNAME.dbo.vw_DimFoo
(The backslash "\" at the beginning suppresses a line break. To define a single-line string using several lines, add backslashes after each line.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With