用Tornado写东西,在查询SQL时出现了这个错误:

#Python3下
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: format requires a mapping

很亦可赛艇,是一个关于格式化字符串的问题,出问题的是下面这条SQL语句:

 sqlcmd_author = "SELECT * FROM `shici_authors` WHERE `name` LIKE '%%s%'"%(name)

后面找到了解决方案,多打几个百分号:

sqlcmd_author = "SELECT * FROM shici_authors WHERE name LIKE '%%%%%s%%%%'"%(                   name)

然而还没有完,Web项目为了防止SQL注入,使用了:

#db_cur.execute(sqlcmd_author,parameter)
sqlcmd_author = "SELECT * FROM shici_authors WHERE name LIKE '%%%%%s%%%%'"
db_cur.execute(sqlcmd_author,(name))
#output:
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '李白'%%'' at line 1")

我勒个去,网上也没详细的说,最后终于找到了解决方法:

sqlcmd_author = "SELECT * FROM shici_authors WHERE name LIKE %s" #不要给%s加单/双引号,pymysql会自动转义
db_cur.execute(sqlcmd_author,('%' + name + '%'))

有效命中。

文章版权:远望江来 - 人的一生当然要靠自我奋斗,当然也要考虑历史的行程

本文链接:https://blog.chutian.bid/archives/62.html

转载请注明文章原始出处 !

添加新评论

返回顶部
Typecho 强力驱动. © Powered by Zhangtinghui. Theme by Postbird.