python 更新游标问题 - %s 符号错误?

标签 python

这可能是一个非常的愚蠢问题,但我已经研究了几个小时但无法解决。

所以这里是:

 def updateEntryAsYoutubeProcessing(self,conn,id):
            cursor = conn.cursor()
            try:
                    numberAffected = cursor.execute("update new_files set is_youtube = 1 where id=%s",(id))
                    conn.commit()
            except MySQLdb.IntegrityError,e:
                    logging.warn("update failed with error \n\t%d:%s",e.args[0],e.args[1])
                    raise
            finally:
                    cursor.close()

此代码总是导致错误:

  Traceback (most recent call last):
  File "mydaemon.py", line 28, in loopForEachFileInDirectory
    self.updateEntryAsYoutubeProcessing(conn,id)
  File "mydaemon.py", line 80, in updateEntryAsYoutubeProcessing
    numberAffected = cursor.execute("update new_files set is_youtube = 1 where id=%s",(id))
  File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 166, in execute
    self.errorhandler(self, exc, value)
  File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 35, in defaulterrorhandler
    raise errorclass, errorvalue
  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 '%s' at line 1")

我已经尝试过使用双引号、三个双引号、将 sql 定义为变量并放入执行中的代码,以及我能想到的一切。

我错过了什么?

我已经在数据库上尝试了 sql,它工作正常(用值替换 %s,obvi)。

编辑: 好吧,所以我真正遇到的问题是 id 为 None。我遇到的下一个问题是,正如答案中所述(谢谢!),我需要将 (id) 转换为 (id,),因为元组。

既然它是一个元组,我就会抛出“Nonetype”错误。谢谢大家,显然我正在修复我的代码以使用类型(并且也不将 None 注入(inject)到数据库中)

最佳答案

参数必须是序列,并且 (id) 不是元组,但 (id,) 是。试试这个:

cursor.execute("update new_files set is_youtube = 1 where id=%s",(id,))

关于python 更新游标问题 - %s 符号错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9105407/

相关文章:

python - pandas groupby 不适用于 3 列

python - 以性能方式扩展 python/numpy 的最佳方法

Python 3 不适用于 Sublime Text 2

python - 在 Celery 任务中获取生成文件的 URl 的最佳方法是什么

python - 带有 mkdocstrings 的 MkDocs 无法提供 "Could not collect"错误

python - 在正则表达式中包含半空格 (\u200c)

python - 如何更改 pySerial 中的行终止符(行尾字符,EOL)

python - 使用 django 表单获取请求公开数据

python - 通过放置括号来最大化表达式的动态规划解决方案

javascript - 从 HTML 表获取 href 链接的策略