我不理解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))
答案 0 :(得分:21)
您转义%%
,但然后首先将字符串用作格式化程序 :
"...." % table,
返回一个新字符串,其中%%
转义百分比被单个%
字符替换。 MySQL数据库适配器(ab)也使用%
的字符串格式,因此它将获取该输出并期望能够使用转义的SQL文字填充%s
个插槽。正是在那里,SQL语句的'%Y-%m-%d'
部分再次被解释为字符串格式并且抛出错误。
解决方案是将倍增加倍:
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语句,其中%%
转义符转换为单个%
个字符。
答案 1 :(得分:3)
最后,@ Martijn Pieters你完全正确。谢谢你的有用答案。另一个错误来自SUM和COUNT。在处理JSON时,Python有时会以疯狂的方式运行。所以完整的答案是:
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,))