19

我不明白 Y 的 ValueError。我用 % 转义...

table = town+"_history"
db.execute("SELECT DATE_FORMAT(snapdate,'%%Y-%%m-%%d') AS date, SUM( population ) AS accountpopulation, count( blockid ) AS number_block FROM %s WHERE blockid =%%s GROUP BY snapdate ORDER BY snapdate DESC LIMIT 7" % table, (blockid))
4

2 回答 2

40

您先转义,%%然后将字符串用作格式化程序:

"...." % table,

返回一个新字符串,其中%%转义的百分比被单个%字符替换。% MySQL 数据库适配器 (ab)也使用字符串格式,因此它将获取该输出并期望能够%s用转义的 SQL 文字填充插槽。在那里,您'%Y-%m-%d'的 SQL 语句部分再次被解释为字符串格式并引发错误。

解决方案是加倍加倍:

db.execute("SELECT DATE_FORMAT(snapdate,'%%%%Y-%%%%m-%%%%d') AS date, SUM( population ) AS accountpopulation, count( blockid ) AS number_block FROM %s WHERE blockid = %%s GROUP BY snapdate ORDER BY snapdate DESC LIMIT 7" % table, (blockid,))

str.format()改用并避免双重转义:

db.execute("SELECT DATE_FORMAT(snapdate,'%%Y-%%m-%%d') AS date, SUM( population ) AS accountpopulation, count( blockid ) AS number_block FROM {0} WHERE blockid = %s GROUP BY snapdate ORDER BY snapdate DESC LIMIT 7".format(table), (blockid,))

这里{0}被表名替换,%%转义符保持不变;数据库适配器将使用该%s槽填充blockid参数并返回一条 SQL 语句,其中%%转义符变成单个%字符。

于 2013-05-13T21:06:41.943 回答
3

最后,@Martijn Pieters 你是完全正确的。并感谢您的有用回答。另一个错误来自 SUM 和 COUNT。Python 在处理 JSON 时有时会以一种疯狂的方式运行。所以完整的答案是:

db.execute("SELECT DATE_FORMAT(snapdate,'%%%%Y-%%%%m-%%%%d') AS date, CAST(SUM( population ) AS CHAR ) AS accountpopulation, CAST(count( blockid ) AS CHAR) AS number_block FROM %s WHERE blockid = %%s GROUP BY snapdate ORDER BY snapdate DESC LIMIT 7" % table, (blockid,))
于 2013-05-14T09:54:48.970 回答