1

I have a MySQL query that is stored in a python string. It looks like this;

query = """ SELECT colA, colB
            FROM table WHERE colC = '1' """

Suppose I want to insert string variable to construct the same query.

Can I do something similar to this?

Var1 = 'colA'
Var2 = 'colB'
query = """ SELECT %s, %s
                FROM table WHERE colC = '1' """, Var1, Var2 

How can I do this in python? I am using Python 2.7

1
  • Can someone explain why the negative vote? I believe it is a common problem. Commented Aug 13, 2014 at 11:00

1 Answer 1

1

You cannot use column names as SQL parameters; you'll have to manually interpolate the name; you could use str.format() string formatting for this:

query = """ SELECT `{}`, colB
            FROM table WHERE colC = '1' """.format(Var1)

The ` backticks around the {} placeholder serve to make sure your column identifier is interpreted as such even if it contains whitespace or a name that is a keyword otherwise.

Multiple columns take multiple placeholders:

query = """ SELECT `{}`, `{}`
            FROM table WHERE colC = '1' """.format(Var1, Var2)

Be extremely careful when doing this and always pre-validate that Var1 is a valid column name. Don't blindly accept user input as you will not be protected from SQL injection attacks otherwise.

Sign up to request clarification or add additional context in comments.

3 Comments

What if I have 2 variables - Var1 and Var2. Say Var2 = colB. How will the code looks like? I have edited my question accordingly.
@user3293156: use multiple {} placeholders, and pass multiple arguments to the str.format() method: """SELECT `{}`, `{}` FROM ...""".format(Var1, Var2).
Thank you. You are most helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.