Python 3.x 如何修复此dict和postgreSQL
我只想更新我的键,我的dict中的值 这是用于使用python dict更新PostgreSQL的Python 3.x 如何修复此dict和postgreSQL,python-3.x,postgresql-9.3,Python 3.x,Postgresql 9.3,我只想更新我的键,我的dict中的值 这是用于使用python dict更新PostgreSQL的 data ={ 'created_by':'obama', 'last_updated_by':'nandu', 'effective_from':'2019-12-30', 'effective_to':'2017-12-30' } lst= list() lst1 = list() for key,value
data ={
'created_by':'obama',
'last_updated_by':'nandu',
'effective_from':'2019-12-30',
'effective_to':'2017-12-30'
}
lst= list()
lst1 = list()
for key,value in data.items():
lst.append(key)
lst1.append(value)
keys = tuple(lst)
values = tuple(lst1)
update = "UPDATE table_name SET %s = %s where name = 'kumar'"
cur.execute(update,(keys,values))
我想将键设置为字段名,将值设置为值
但是我得到的字段名(键)是字符串
所以我得到了语法错误您不能将元组用于SET。最好是在dict上循环,每次设置一个键:
data ={'created_by':'obama',
'last_updated_by':'nandu',
'effective_from':'2019-12-30',
'effective_to':'2017-12-30',
}
for key, value in data.items():
update = "UPDATE table_name SET %s = %s where name = 'kumar'"
cur.execute(update,(key, value))
或者按照建议使用f字符串
data ={'created_by':'obama',
'last_updated_by':'nandu',
'effective_from':'2019-12-30',
'effective_to':'2017-12-30',
}
arguments = ','.join([f'{key}=\'{val}\'' for key, val in data.items()])
update = f"UPDATE table_name SET {arguments} where name = 'kumar'"
cur.execute(update)
您不需要
lst
、lst1
、键和值的临时变量。您可以使用assignments=['%s=%s%%(key,value)作为数据中的key,value.items()]
set\u子句='set%s'%assignments
update=“update table\u name%s其中name='kumar'%set\u子句