这可能是一个真的愚蠢的问题,但我已经看了几个小时而无法解决它。
所以这里是:
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,它运行正常(用%obv代替%s)。
编辑:
好吧,所以我真的的问题是那个id是None。我遇到的下一个问题是,如答案中所述(谢谢!),我需要将(id)
变为(id,)
,因为元组。
既然它是一个元组,我会抛出一个“Nonetype”错误。谢谢大家,显然我正在修改我的代码以使用typles(并且也不会将无注入到数据库中)
答案 0 :(得分:3)
参数必须是序列,(id)不是元组,但(id,)是。试试这个:
cursor.execute("update new_files set is_youtube = 1 where id=%s",(id,))
答案 1 :(得分:1)
尝试将其作为数组传递,如docs中所示。
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
答案 2 :(得分:1)
the squence type is (variable,) so you have this type error message;
Traceback (most recent call last): File "./lock.py", line 16, in cur.callproc("ldap_lock", {tckimlik} ) TypeError: arguments must be a sequence
try
cursor.callproc("sp_name", (id,))