我有一个更新数据库 (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
提前致谢。
最佳答案
试试这个:
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)
关于python - 从字典创建 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20118022/