I am trying to create a re-usable mysql statement for updating from a dictionary where the keys are the database fields and the data to go into that field is the value associated with it in the dictionary. This was easy when creating a function for inserting into mysql because it just involved two lists. Now, I need to break apart the lists.
Here is what I have to work with.
fields = self.dictionary.keys()
vals = self.dictionary.values()
stmt = "UPDATE TABLE table_name SET %s = '%s'" %(.join(fields), .join(vals))"
This outputs a statement like:
UPDATE TABLE table_name SET column1, column2 = ('value1','value2')
I need it to output to standard format for updating a table like:
UPDATE table_name SET column1=value1, column2=value2
Notice the WHERE clause in the UPDATE statement. The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records in the table will be updated!
In order to update the value of an associated key, Python Dict has in-built method — dict. update() method to update a Python Dictionary. The dict. update() method is used to update a value associated with a key in the input dictionary.
You don't want to be putting literal values in using string interpolation - SQL injection attacks are not a Good Thing(tm). Instead, you use the placeholder syntax relevant for your database (I think MySQL's is '%s').
Note: I'm using .format
here, change to use % if you want, but escape any %'s
d = {'col1': 'val1', 'col2': 'val2'}
sql = 'UPDATE table SET {}'.format(', '.join('{}=%s'.format(k) for k in d))
print sql
# 'UPDATE table SET col2=%s, col1=%s'
Assuming cur
is a DB cursor the correct way to perform the query is:
cur.execute(sql, d.values())
This works because although the ordering of a dictionary is effectively arbitrary order, the order of keys/values of a dict will be consistent such that dict(zip(d.keys(), d.values())) == d
.
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