bharal bharal - 1 month ago 7
Python Question

python update cursor issue - error with %s symbol?

this is probably a really stupid problem, but i've been looking at it for a few hours and cannot work it out.

So here goes:

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()


this code always results in an error:

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")


I've tried my code with double quotes, triple double quotes, the sql defined as a variable and placed in the execute, everything i can think of.

What am i missing?

I've tried the sql on the database, and it works fine (substituting the %s with a value, obvi).

EDIT:
ok, so the problem i was really having was that id was None. The next problem i was having was that, as noted in the answers (thanks!), I needed to make the
(id)
into
(id,)
, because tuples.

Now that it is a tuple, I get a "Nonetype" error thrown. Thanks all, obviously i'm fixing my code to use typles (and also to not inject None into the db)

Answer

The arguments must be a sequence and (id) is not a tuple, but (id,) is. Try this:

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