user3074823
user3074823

Reputation: 53

Python & Mysql : Select statement with variable

Hi I was looking for a similar thread but couldn't find any so decided to post. Any hint or link would be appreciated.

I'm using python 2.7 + MySQLdb, I made a sql statement but having a weird issue.

【works】

Val3 = 1
sql = """SELECT ValA FROM %s WHERE Val2 = %s AND Val3 = %s""" % (Val1, Val2, Val3)

【doesn't work】

Val3 = "variable"
sql = """SELECT ValA FROM %s WHERE Val2 = %s AND Val3 = %s""" % (Val1, Val2, Val3)

When I use text as a variable sql statement doesn't get executed.

(Note: no error message just gets treated like as if its not there)

Does anyone know what the problem is?

Upvotes: 2

Views: 33990

Answers (1)

crazyzubr
crazyzubr

Reputation: 1082

Add quotes:

sql = """SELECT ValA FROM `%s` WHERE Val2 = '%s' AND Val3 = '%s'""" % (Val1, Val2, Val3)

Upvotes: 11

Related Questions