Reputation: 875
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
""")
Upvotes: 2
Views: 3605
Reputation: 585
I prefer using f-Strings!
vdf = vertica.select_dataframe(f"""
Select
col1
col2
coln
FROM
TableX
WHERE
col2 IN (21, 22, {AGE})
Group BY 1
""")
Upvotes: 0
Reputation: 2362
I will add one more answer with a dict
unpacking as it made my life much simpler. Using @hexerei-software's INSERT
example:
AGE = raw_input("Enter your age: ")
GENDER = raw_input("Enter your gender (m/f): ")
HEIGHT = raw_input("Enter your height in cm: ")
settings = {'AGE': AGE, 'GENDER': GENDER, 'HEIGHT': HEIGHT}
vdf = vertica.select_dataframe("""
INSERT INTO stats (
age,
gender,
height
)
VALUES
(
'{AGE}',
'{GENDER}',
'{HEIGHT}'
)
""".format(**settings))
Upvotes: 0
Reputation: 3160
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 ))
Upvotes: 6
Reputation: 820
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'
Upvotes: 4
Reputation: 238697
You could make the query string separate and use format to put correct age, e.g.:
a_query = """
Select
col1
col2
coln
FROM
TableX
WHERE
col2 IN (21, 22, {})
Group BY 1
"""
vdf = vertica.select_dataframe(a_query.format(AGE))
Upvotes: 2