【问题标题】:how to format variables before db to avoid errors如何在db之前格式化变量以避免错误
【发布时间】:2010-10-13 05:43:43
【问题描述】:

我收到类似这样的错误:

_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)`

显然' 字符和其他字符可能会导致问题。

如何格式化这些 URL 以避免这种情况?

【问题讨论】:

标签: python mysql


【解决方案1】:

MySQLdb 模块做插值:

cursor.execute("""SELECT * FROM LINKS WHERE link = %s LIMIT 1""",
    (item['link'].encode("utf-8"),)
)

execute() 函数可以传递要替换到查询中的项目(请参阅the documentation for execute())。它会根据数据库查询的需要自动转义。

如果您更喜欢使用字典而不是元组来指定要替换的内容:

cursor.execute("""SELECT * FROM LINKS WHERE link = %(link)s LIMIT 1""",
    {'link': item['link'].encode("utf-8")}
)

【讨论】:

  • 取消...只是在我的 sql 字符串与 execute 分开的版本中出错
  • 为了完整起见,应注意替换字符(%s?%(withdictionary)s)因 DB 模块而异,因为 PEP 249 允许不同的参数样式。
猜你喜欢
  • 2011-05-05
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
  • 2020-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多