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?
It is possible to update multiple rows in a single SQL Query. You can also call it a bulk update. Use the cursor. executemany() method of cursor object to update multiple rows of a table.
MySQL UPDATE command can be used to update multiple columns by specifying a comma separated list of column_name = new_value. Where column_name is the name of the column to be updated and new_value is the new value with which the column will be updated.
ALTER statement of SQL With the ALTER statement, one can add, drop, or modify a column of an existing table as well as modify table constraints. The syntax for adding a column with ALTER statement: ALTER TABLE table_name ADD new_column_name column_definition [FIRST | AFTER column_name];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With