[英]python StringBuilder for MySQL query execution
I am trying to query my database where one of the columns is a python variable: 我试图查询我的数据库,其中一列是一个python变量:
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
. 请注意,SQL表:
golden_table
包含4列: week2 week3 week4 week5
。 However, python or MySQL is not treating the value of weekNum
as a column. 但是,python或MySQL不会将
weekNum
的值视为列。 Instead what is returned from the query is the value "weeki." 而是从查询返回的是值“weeki”。 where i is as above.
我在哪里。 In Java, I know the way around this is the
StringBuilder
class. 在Java中,我知道解决这个问题的方法是
StringBuilder
类。
All help is appreciated, and let me know if you need more information. 感谢所有帮助,如果您需要更多信息,请与我们联系。
If your python version is recent (2.6+). 如果你的python版本是最近的(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]))
Parameter replacement in execute
is for values, not fieldnames. execute
参数替换是值,而不是字段名。 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. 注意第一个语句中的双重百分比,以便它们毫发无损地通过字符串插值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.