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 assoc
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
.
how about trying
stmt = "UPDATE TABLE table_name SET "
for k,v in di.items():
stmt += "%s = %s, " %(k,v)
stmt = stmt[-2:]