gpt4 book ai didi

python - Sqlite 认为我缺少绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-03 16:35:57 25 4
gpt4 key购买 nike

由于缺乏有关如何在 Python 中从字典创建 sqlite 查询的任何资料,我构建了自己的查询:

    updates = ', '.join(["`"+field+"`" + '=:'+field for field in information.keys() if field != 'name'])
where = ' WHERE name == :name'
values = {':'+field: value for field, value in information.items()}

query = 'UPDATE firms SET ' + updates + where
c.execute(query, values)

但是,我明白了

sqlite3.ProgrammingError: You did not supply a value for binding 1.

这让我感到困惑,因为我认为我已经提供了我应该提供的一切:

In[374]: query
Out[374]: 'UPDATE firms SET `founded`=:founded, `size`=:size, `headquarters`=:headquarters, `type`=:type, `revenue`=:revenue WHERE name == :name'
In[375]: information
Out[375]:
{'founded': '1962',
'headquarters': 'Bentonville, AR',
'name': 'Walmart',
'revenue': '$10+ billion (USD) per year',
'size': '10000+ employees',
'type': 'Company - Public (WMT)'}

最佳答案

您不需要 values 键中的 :。试试这个:

values = {field: value for field, value in information.items()}

或者,更简洁地说:

values = information

示例程序:

import sqlite3

conn = sqlite3.connect(":memory:")
c = conn.cursor()

c.execute("create table firms (founded, hq, name, rev, size, type)")
c.execute("insert into firms ( name ) values (?) ",("bar", ))
conn.commit()

def update(information):
updates = ', '.join(["`"+field+"`" + '=:'+field for field in information.keys() if field != 'name'])
where = ' WHERE name == :name'
values = information
query = 'UPDATE firms SET ' + updates + where
c.execute(query, values)
conn.commit()

update(dict(name='bar', founded='1062', rev='1 MILLION DOLLARS!'))
print c.execute('select * from firms').fetchall()

结果:

[(u'1062', None, u'bar', u'1 MILLION DOLLARS!', None, None)]

关于python - Sqlite 认为我缺少绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37211448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com