views:

566

answers:

2

Hi

I'm trying to get this Python MYSQL update statement correct(With Variables):

cursor.execute ("UPDATE tblTableName SET Year=%s" % Year ", Month=%s" % Month ", Day=%s" % Day ", Hour=%s" % Hour ", Minute=%s" Minute "WHERE Server=%s " % ServerID)

Any ideas where I'm going wrong?

A: 

It should be:

cursor.execute ("""
   UPDATE tblTableName
   SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
   WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))

You can also do it with basic string manipulation,

cursor.execute ("UPDATE tblTableName SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s WHERE Server='%s' " % (Year, Month, Day, Hour, Minute, ServerID))

but this way is discouraged because it leaves you open for SQL Injection. As it's so easy (and similar) to do it the right waytm, do it correctly.

The only thing you should be careful, is that some database backends don't follow the same convention for string replacement (SQLite comes to mind).

voyager
Paolo's answer is better. http://stackoverflow.com/questions/1307378/python-mysql-update-statement/1307413#1307413
voyager
But this one will work with every backend. This version doesn't do any validation on the input, while Paolo's way will make sure to escape the variables content.
voyager
Do *not* do it this way. You leave yourself wide open to SQL injection attacks. Paulo has the right answer, because it ensures that the values are properly escaped before passing them to the db.
Daniel Roseman
Ripped off Paolo's answer, as I can't delete accepted answer.
voyager
+6  A: 

You've got the syntax all wrong:

cursor.execute ("""
   UPDATE tblTableName
   SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
   WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))

For more, read the documentation.

Paolo Bergantino
+1 you were faster than me :)
Nadia Alramli