You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python-SQLite3脚本语法问题:如何查询指定列值的所有行?

Python SQLite3 查询指定喜好饮品用户的错误修复与正确写法

错误原因解析

你遇到的sqlite3.ProgrammingError: Incorrect number of bindings supplied错误,核心问题是参数传递格式错误:
当你给execute()传入字符串'Cola'时,SQLite会将其视为字符序列,拆分成'C'、'o'、'l'、'a'四个独立值,但你的SQL语句只声明了1个占位符?,导致绑定数量不匹配。

正确的方法实现

需要将单个参数包装成元组(注意末尾的逗号不能省略,否则会被识别为单个值而非元组),同时单个值匹配用=比IN(?)更直观:

def get_fav_drink_folks(self, drink):
    sql = """SELECT * FROM database WHERE fav_drink = ?"""
    # 必须用元组传递参数,逗号是关键
    self.cur.execute(sql, (drink,))
    # fetchall()获取所有匹配行,fetchmany()默认仅返回1行
    return self.cur.fetchall()

额外优化建议

  1. 避免使用SQL关键字作为表名
    database是SQLite的关键字,建议修改表名(比如user_preferences),避免潜在语法冲突:
def create_table(self):
    table = """CREATE TABLE IF NOT EXISTS
        user_preferences (name TEXT PRIMARY KEY,
                  fav_food TEXT,
                  fav_drink TEXT
                  )"""
    self.cur.execute(table)
    self.con.commit()

同步修改插入、查询语句中的表名即可。

  1. 批量插入优化
    用executemany()替代循环插入,提升数据写入效率:
def insert_batch_data(self, items_list):
    sql = """INSERT OR IGNORE INTO user_preferences VALUES(?,?,?)"""
    self.cur.executemany(sql, items_list)
    self.con.commit()

主函数中直接调用db.insert_batch_data(data)即可,无需循环遍历。

内容的提问来源于stack exchange,提问作者Sun Bear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 13:07:42