I have a python script that contains a sql query. I use triple quotes around the sql query for formatting purposes. I'd like to inject variables that I populate from the command line into the query. How can I do this while preserving the triple quotes. Are there better ways to get around the triple quotes?
Ex:
AGE = raw_input("Enter your age: ")
vdf = vertica.select_dataframe("""
Select
col1
col2
coln
FROM
TableX
WHERE
col2 IN (21, 22, AGE)
Group BY 1
""")
I am surprised, that the fabulous % operator is not mentioned, pythons build in string formatting would make your original lines work with a tiny modification:
AGE = raw_input("Enter your age: ")
vdf = vertica.select_dataframe("""
Select
col1,
col2,
coln
FROM
TableX
WHERE
col2 IN (21, 22, %s)
Group BY 1
""" % AGE)
This would also work for queries with multiple arguments:
AGE = raw_input("Enter your age: ")
GENDER = raw_input("Enter your gender (m/f): ")
HEIGHT = raw_input("Enter your height in cm: ")
vdf = vertica.select_dataframe("""
INSERT INTO stats (
age,
gender,
height
)
VALUES
(
'%s',
'%s',
'%s'
)
""" % ( AGE, GENDER, HEIGHT ))
You can use format like this:
AGE = raw_input("Enter your age: ")
query_1 = """
Select
col1
col2
coln
FROM
TableX
WHERE
col2 IN (21, 22, {})
Group BY 1
"""
vdf = vertica.select_dataframe(query_1.format(AGE))
A simple example with triple quotes and multiple assignments is:
>>> age = 100
>>> name = "koukouviou"
>>> """I am {} and I am {} years old""".format(name, age)
'I am koukouviou and I am 100 years old'
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