从字典创建SQL查询

时间:2013-11-21 10:13:03

标签: python mysql sql dictionary

我有一个更新数据库(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

提前致谢。

2 个答案:

答案 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,))

需要注意的一些要点:

  1. 由于字典是无序的,我们首先提取密钥列表。
  2. 而不是将值直接放在查询中;您应该将它们传入。再次,我们逐步执行相同的键列表,以使值与列名匹配。
  3. 最后,我们将id添加到查询的有序参数集中。