gpt4 book ai didi

Python => 值错误 : unsupported format character 'Y' (0x59)

转载 作者:IT王子 更新时间:2023-10-28 23:46:23 29 4
gpt4 key购买 nike

我不理解 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))

最佳答案

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

"...." % table,

返回一个新字符串,其中 %% 转义百分比被单个 % 字符替换。 MySQL 数据库适配器 (ab) 使用带有 % too 的字符串格式,因此它将获取该输出并期望能够填充 %s 带有转义 SQL 文字的插槽。在那里,您的 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 语句,其中 %% 转义变成单个 % 个字符。

关于Python => 值错误 : unsupported format character 'Y' (0x59),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16531116/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com