由于缺少有关如何从字典中用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/

10-11 20:01