您先转义,%%
然后将字符串用作格式化程序:
"...." % 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 语句,其中%%
转义符变成单个%
字符。