Python MYSQL update statement

Question:

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?

Asked By: Adam Chetnik

||

Answers:

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

Answered By: Esteban Küber

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.

Answered By: Paolo Bergantino

Here is the correct way:

import MySQLdb

if __name__ == '__main__':
    connect = MySQLdb.connect(host="localhost", port=3306,
                              user="xxx", passwd="xxx", db='xxx', charset='utf8')

    cursor = connect.cursor()

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

    connect.commit()
    connect.close()

P.S. Don’t forget connect.commit(), or it won’t work

Answered By: Little Roys

Neither of them worked for me for some reason.

I figured it out that for some reason python doesn’t read %s. So use (?) instead of %S in you SQL Code.

And finally this worked for me.

   cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))
   connect.commit()
Answered By: SVK

@Esteban Küber is absolutely right.

Maybe one additional hint for bloody beginners like me.
If you speciify the variables with %s, you have to follow this principle
for EVERY input value, which means for the SET-variables as well as for the WHERE-variables.

Otherwise, you will have to face a termination message like
‘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 WHERE’

Answered By: M. Straube