I am trying to query my database where one of the columns is a python variable:
weekNum = "week" + str(i) #i is either 2, 3, 4, 5
cur.execute("select %s from golden_table where nGram = %s and hash_tag = %s", (weekNum, tup[0], tup[1]))
Note that the SQL table: golden_table includes the 4 columns: week2 week3 week4 week5.
However, python or MySQL is not treating the value of weekNum as a column. Instead what is returned from the query is the value "weeki." where i is as above. In Java, I know the way around this is the StringBuilder class.
- What is the equivalent way of solving this problem in python?
- What is a better way to solve this in python?
All help is appreciated, and let me know if you need more information.
2 Answers 2
If your python version is recent (2.6+). You could use format.
weekNum = "week" + str(i) #i is either 2, 3, 4, 5
query = "select {0} from golden_table where nGram = %s and hash_tag = %s".format(weekNum)
cur.execute(query, (tup[0], tup[1]))
Comments
Parameter replacement in execute is for values, not fieldnames. You'll need to use normal string interpolation for that. So:
sql = "select %s from golden_table where nGram = %%s and hash_tag = %%s" % weekNum
cur.execute(sql, tup)
Note the double percents in the first statement so that they pass through the string interpolation unscathed.
Comments
Explore related questions
See similar questions with these tags.