Python 2.7.8:TypeError:%d format:需要一个数字,而不是元组

时间:2016-05-02 11:06:21

标签: python mysql python-2.7

当我写简单时:

sqli = ("SELECT SUM(obtained) FROM stobt  WHERE stid = %d " ) %(row2)

没有错误并打印,

但是当我写道:

sqli = ("SELECT SUM(obtained) FROM stobt  WHERE stid = %d and subject='%s'" ) %(row2,sub)

给了我一个让我生病的错误:

错误:

TypeError: %d format: a number is required, not tuple

更多这里是我的数据库: enter image description here

1 个答案:

答案 0 :(得分:0)

您的问题必然会创建查询字符串,并且与真实数据库(尚未)无关。

如果row2是一个整数而sub是一个字符串,那么它适用于我:

>>> row2 = 12
>>> "SELECT SUM(obtained) FROM stobt  WHERE stid = %d " % (row2)
'SELECT SUM(obtained) FROM stobt  WHERE stid = 12 '
>>> sub = "subject"
>>> "SELECT SUM(obtained) FROM stobt  WHERE stid = %d and subject='%s'" % (row2, sub)
"SELECT SUM(obtained) FROM stobt  WHERE stid = 12 and subject='subject'"
>>> ("SELECT SUM(obtained) FROM stobt  WHERE stid = %d and subject='%s'") % (row2, sub)
"SELECT SUM(obtained) FROM stobt  WHERE stid = 12 and subject='subject'"
>>> type(row2)
int

请确保您没有更改row2的值。