尝试INSERT到MySQL时不断出错

时间:2014-03-27 02:28:37

标签: python mysql sql

每次我尝试在Python脚本中将数据插入MySQL表时,我都会遇到同样的错误:

tools.cerabot@tools-login:~/wikitool-tasks2$ python didyouknow.py
didyouknow.py:62: Warning: Table 'did_you_know' already exists
  self.cursor.execute(self.create_query)
Traceback (most recent call last):
  File "didyouknow.py", line 121, in <module>
    test._parse_page()
  File "didyouknow.py", line 109, in _parse_page
    self.cursor.execute(record_exists.format(item["name"]))
  File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
    self.errorhandler(self, exc, value)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.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 ':Did you know nominations/Cirrus (song)' at line 1")

此代码可在GitHub上公开查看,但您对95到第116行特别感兴趣。我已尝试转义和解码字符串,修改我的查询,没什么。 (不可否认,我是一名基本的MySQL程序员。)在该领域有经验的人能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

问题在于&#34;有趣的角色&#34;在您的维基百科标题中正在搞乱SQL语法。你需要处理它。这可以通过转义来完成,但最好的做法是使用SQL参数化,如下所示:

record_exists = u"SELECT COUNT(*) FROM did_you_know WHERE " \
                "name = %s"
# and later on
self.cursor.execute(record_exists, item["name"])

你以后实际上已经这样做了(第112行)。