Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python MYSQL update statement

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?

like image 969
Adam Chetnik Avatar asked Aug 20 '09 16:08

Adam Chetnik


People also ask

How do you update multiple rows in Python?

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.

How do I update multiple columns in mysql?

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.

How do you use alter in Python?

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];


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

like image 190
Esteban Küber Avatar answered Sep 20 '22 09:09

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.

like image 37
Paolo Bergantino Avatar answered Sep 18 '22 09:09

Paolo Bergantino