我有一个更新数据库(MySQL)中的条目的功能,它需要尽可能动态。
该函数允许API的用户传递记录的id,然后kwargs处理要更改的值(对可以传递的值的数量没有限制)。
所以我想说我从kwargs那里得到这本词典
{'hello':'world', 'foo':'bar'}
有没有办法可以在更新语句中使用它。
UPDATE myTable
SET key_n = val_n, key_n+1 = val_n+1, ...
WHERE id = the_id_passed_to_the_function
提前致谢。
答案 0 :(得分:4)
试试这个:
def UpdateQuery(data,where):
if isinstance(data, dict) and where:
vals = ','.join(["%s=?" %(k) for k,v in data.iteritems()])
query = "update myTable set %s where id=?" % (vals)
res = cr.execute(query,where)
答案 1 :(得分:0)
怎么样:
foo = kwargs['bar']
id = 1
if foo:
k = foo.keys()
q = '''UPDATE myTable'''
q += ','.join('SET {0}=%s'.format(i) for i in k)
q += 'WHERE id = %s'
cur.execute(q,tuple(foo[i] for i in k)+(id,))
需要注意的一些要点: