Search code examples
pythonmysqlstringstring-interpolation

Python arguments inside triple quotes


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

Solution

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