在尝试插入MySQL时总是出错

2024-06-06 13:25:53 发布

您现在位置:Python中文网/ 问答频道 /正文

每次尝试在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")

虽然您对95到116行特别感兴趣,但它的代码在GitHub上是公开可见的。我尝试过对字符串进行转义和unicoding,修改我的查询,什么都没有。(不可否认,我是一个基本的MySQL程序员)有没有经验的人可以帮我弄清楚这个问题?在


Tags: inpyselfyouexecuteparseexistsline
1条回答
网友
1楼 · 发布于 2024-06-06 13:25:53

问题是维基百科标题中的“搞笑字符”扰乱了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行)。在

相关问题 更多 >