我必须为 postgresql 构建一个动态更新查询。 它是动态的,因为我必须事先确定要更新哪些列。
给定一个示例表:
create table foo (id int, a int, b int, c int)
然后我将以编程方式构建“set”子句
_set = {}
_set['a'] = 10
_set['c'] = NULL
之后我必须构建更新查询。在这里我被困住了。 我必须构造这个 sql 更新命令:
update foo set a = 10, b = NULL where id = 1
如何使用 psycopg2 参数化命令执行此操作? (即,如果它不为空则循环遍历 dict 并构建 set 子句)?
更新
在我 sleep 的时候,我自己找到了解决方案。它是动态的,正是我想要的样子:-)
create table foo (id integer, a integer, b integer, c varchar)
updates = {}
updates['a'] = 10
updates['b'] = None
updates['c'] = 'blah blah blah'
sql = "upgrade foo set %s where id = %s" % (', '.join("%s = %%s" % u for u in updates.keys()), 10)
params = updates.values()
print cur.mogrify(sql, params)
cur.execute(sql, params)
结果就是我需要的内容和方式(尤其是可为空和可引用的列):
"upgrade foo set a = 10, c = 'blah blah blah', b = NULL where id = 10"
最佳答案
实际上有一种更简洁的方法,使用 the alternative column-list syntax :
sql_template = "UPDATE foo SET ({}) = %s WHERE id = {}"
sql = sql_template.format(', '.join(updates.keys()), 10)
params = (tuple(addr_dict.values()),)
print cur.mogrify(sql, params)
cur.execute(sql, params)
关于python - 在 psycopg2 中构建动态更新查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34774409/