Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
    
Can someone explain why the negative vote? I believe it is a common problem. –  user3293156 Aug 13 at 11:00
    
try %(Var1, Var2) –  user1935024 Aug 13 at 11:17

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
    
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 Aug 13 at 11:03
    
@user3293156: use multiple {} placeholders, and pass multiple arguments to the str.format() method: """SELECT `{}`, `{}` FROM ...""".format(Var1, Var2). –  Martijn Pieters Aug 13 at 11:03
    
Thank you. You are most helpful. –  user3293156 Aug 13 at 11:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.