我正在尝试查询我的数据库,其中一列是 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”。其中 i 如上所述。在 Java 中,我知道解决这个问题的方法是使用 StringBuilder 类。
- 在 python 中解决这个问题的等效方法是什么?
- 在 python 中解决这个问题的更好方法是什么?
感谢所有帮助,如果您需要更多信息,请告诉我。
最佳答案
如果您的 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]))
关于用于 MySQL 查询执行的 python StringBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17779005/