【发布时间】:2020-12-27 11:01:43
【问题描述】:
我尝试通过 LIKE 子句获取标题中包含“the”一词的电影的数量。在 Python 连接器 MySQL 中:
word='the'
query = """ SELECT COUNT(title) from movies WHERE title LIKE '%%%s%%' """ % (word,)
cursor.execute(query)
# error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT COUNT(title) from movies WHERE title LIKE '%the%'' at line 1
p = "the"
query = ("SELECT COUNT(title) from movies WHERE title LIKE", ("%" + p + "%",))
cursor.execute(query,(p,))
# AttributeError: 'tuple' object has no attribute 'encode'
【问题讨论】:
-
您没有将任何绑定参数放入第二个查询中。
, ("%" + p + "%",)不仅将它标记到查询的末尾,它还将参数解压缩到一个占位符中。第一个查询可以注入,应该完全避免 -
您的问题出在代码中的某个额外的 ',' 中。当您在 python 中执行
object, object时,它会隐式转换为元组(object, object),因此一些额外的 ',' 将您的部分代码转换为元组。确保您的查询是一个字符串,并且您在 cursor.execute 中正确传递参数。
标签: python mysql sql count sql-like