Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update mysql with python where fields and entries are from a dictionary?

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
like image 990
ccdpowell Avatar asked Jul 17 '12 06:07

ccdpowell


People also ask

Can we use UPDATE with WHERE clause?

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!

How you will UPDATE keys and values in the dictionary?

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.


1 Answers

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.

like image 143
Jon Clements Avatar answered Oct 11 '22 15:10

Jon Clements