![](/img/trans.png)
[英]Is there a way to stop the execution of a mysql query in python if a python exception occurs?
[英]python StringBuilder for MySQL query execution
我试图查询我的数据库,其中一列是一个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]))
请注意,SQL表: golden_table
包含4列: week2 week3 week4 week5
。 但是,python或MySQL不会将weekNum
的值视为列。 而是从查询返回的是值“weeki”。 我在哪里。 在Java中,我知道解决这个问题的方法是StringBuilder
类。
感谢所有帮助,如果您需要更多信息,请与我们联系。
如果你的python版本是最近的(2.6+)。 你可以使用格式。
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]))
execute
参数替换是值,而不是字段名。 你需要使用普通的字符串插值。 所以:
sql = "select %s from golden_table where nGram = %%s and hash_tag = %%s" % weekNum
cur.execute(sql, tup)
注意第一个语句中的双重百分比,以便它们毫发无损地通过字符串插值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.