Python MYSQL update statement Python MYSQL update statement mysql mysql

Python MYSQL update statement


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


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.


Here is the correct way:

import MySQLdbif __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