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

标签 python sqlite

由于缺乏有关如何在 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/

相关文章:

python - Pyramid 、sqlalchemy dbsession

python - 导入错误 : No module named IPython

python - 替代 python 脚本中的 mpirun

sqlite - 如何忽略sqlite3插入失败以允许tcl脚本在失败后继续?

ios - 在 xcode 5 中使用 sqlite 浏览器查看 coredata

python - 使用 ElementTree 添加子元素

python unittest2 - 将测试方法名称暴露给设置方法

python - 从 sqlite 表中提取项目以在 Python 中使用时遇到问题

android - 使用来自 android 中本地 sqlite 数据库的数据填充 recyclerview

Python:如何成功继承Sqlite3.Cursor并添加我的自定义方法