我收到的错误就像这样:
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't Stop.mp3' LIMIT 1' at line 1")
因为在尝试使用以下代码插入或不插入之前,我试图将我的数据库中存在的URL与变量中的URL进行比较:
`#see if any links in the DB match the crawled link
check_exists_sql = "SELECT * FROM LINKS WHERE link = '%s' LIMIT 1" % item['link'].encode("utf-8")
cursor.execute(check_exists_sql)`
显然,'
字符和其他字符可能会导致问题。
如何格式化这些网址以避免这种情况?
答案 0 :(得分:3)
让MySQLdb
模块进行插值:
cursor.execute("""SELECT * FROM LINKS WHERE link = %s LIMIT 1""",
(item['link'].encode("utf-8"),)
)
可以将execute()
函数传递给要替换的查询项(参见the documentation for execute()
)。它将根据数据库查询的需要自动转义。
如果您更喜欢使用dict而不是元组来指定要替换的内容:
cursor.execute("""SELECT * FROM LINKS WHERE link = %(link)s LIMIT 1""",
{'link': item['link'].encode("utf-8")}
)