You do not want to enter literal values ββwhen using string interpolation - SQL injection attacks are not good (tm) . Instead, you use the placeholder syntax that matches your database (I think MySQL is "% s").
Note. I use .format
here, change the use of% if you want, but avoid any%
d = {'col1': 'val1', 'col2': 'val2'} sql = 'UPDATE table SET {}'.format(', '.join('{}=%s'.format(k) for k in d)) print sql
Assuming cur
is a DB cursor, the correct way to execute a query is:
cur.execute(sql, d.values())
This works because although the ordering of the dictionary is actually arbitrary order, the order of the dict keys / values ββwill be consistent, so dict(zip(d.keys(), d.values())) == d
.
source share