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



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

因此:

 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 nt%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定义为变量并放在execute中,我能想到的一切。

我错过了什么?

我在数据库上尝试过sql,它运行良好(用值obvi替换%s)。

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

既然它是一个元组,我就会抛出一个"Nonetype"错误。谢谢大家,很明显,我正在修复我的代码以使用typles(并且不将None注入数据库)

参数必须是一个序列,并且(id)不是元组,但(id,)是

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

尝试将其作为数组传入,如文档中所示。

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

编辑:以下是由于SQL注入漏洞而不应该做的事情的示例-请参阅下面的评论

字符串格式中需要%而不是,

# NOT SAFE
"update new_files set is_youtube = 1 where id=%s" % id

squence类型是(variable,),所以您有这个类型的错误消息;

追踪(最近一次通话):文件"./lock.py",第16行,位于cur.callproc("ldap_lock",{tckimlik})TypeError:参数必须是序列

尝试

cursor.callproc("sp_name",(id,))

最新更新