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 \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替换成一个值)。
编辑:
好吧,我真正遇到的问题是id是None。接下来我遇到的另一个问题是,正如回答中提到的(谢谢大家!),我需要把(id)
改成(id,)
,因为这是元组的写法。
现在它变成元组后,我又遇到了一个“Nonetype”的错误。谢谢大家,显然我正在修正我的代码,使用元组(而且也不往数据库里插入None)。
3 个回答
1
这个错误信息的意思是,你传给函数的参数类型不对。
错误信息的具体内容是:
追踪记录(最近的调用在最前面):
文件 "./lock.py",第 16 行,在
cur.callproc("ldap_lock", {tckimlik})
类型错误:参数必须是一个序列
你可以试试这样写:
cursor.callproc("sp_name", (id,))
1
试着像这里的文档中所示那样,把它作为一个数组传入。
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
3
这个意思是,你传入的参数必须是一个序列,而(id) 不是一个元组,但 (id,) 是一个元组。你可以试试这样写:
cursor.execute("update new_files set is_youtube = 1 where id=%s",(id,))