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

SQLite字符串格式化查询触发OperationalError:无DrugName列问题

问题:查询数据库列时提示“该列不存在”但实际列存在

数据库表结构
我的数据库中存在DrugName列,但执行查询时却收到“该列不存在”的错误。

我的代码

import sqlite3
from sqlite3 import Error

def create_connection(db_file):
    
    conn = None
    try:
        conn = sqlite3.connect(db_file)
    except Error as e:
        print(e)

    return conn

def select_by_slot(conn, slot_name, slot_value):
    """
    查询tasks表中的所有行
    :param conn: 数据库连接对象
    :return:
    """
    cur = conn.cursor()
    cur.execute("SELECT * FROM finale WHERE {}='{}'".format(slot_name, slot_value))

    rows = cur.fetchall()

    if len(list(rows)) < 1:
        print("没有匹配您查询的资源。")
    else:
        print(rows)
        # for row in random.sample(rows, 1):
        #     print(f"Try the {(row[0])}")

select_by_slot(create_connection("ubats.db"),
    slot_name = 'DrugName',slot_value= 'Beclomethasone dipropionate 100mcg and formoterol fumarate dihydrate 6mcg pressurized inhalation solution')

我想要查询特定药物是否存在于该列中,若存在则打印对应行。我尝试过搜索以及使用f-string格式化,但都无效。求解决思路?

错误信息

---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
/Users/karan/udev/ubat_db/talk_db.ipynb Cell 2 in <cell line: 33>()
     29         print(rows)
     30         # for row in random.sample(rows, 1):
     31         #     print(f"Try the {(row[0])}")
---&gt; 33 select_by_slot(create_connection("ubats.db"),
     34     slot_name = 'DrugName',slot_value= 'Beclomethasone dipropionate 100mcg and formoterol fumarate dihydrate 6mcg pressurized inhalation solution')

/Users/karan/udev/ubat_db/talk_db.ipynb Cell 2 in select_by_slot(conn, slot_name, slot_value)
     16 """
     17 Query all rows in the tasks table
     18 :param conn: the Connection object
     19 :return:
     20 """
     21 cur = conn.cursor()
---&gt; 22 cur.execute("SELECT * FROM finale WHERE {}='{}'".format(slot_name, slot_value))
     24 rows = cur.fetchall()
     26 if len(list(rows)) < 1:

OperationalError: no such column: DrugName

解决思路

  • 核对表名一致性:函数注释标注查询tasks表,但实际SQL语句查询的是finale表,先确认图片里的目标表名,把SQL中的表名修正为正确值。
  • 改用参数化查询:当前字符串拼接SQL的方式存在SQL注入风险,还可能因药物名称含特殊字符引发语法错误,修改查询语句为:
    cur.execute(f"SELECT * FROM finale WHERE {slot_name} = ?", (slot_value,))
    
    注:列名无法参数化,需确保slot_name为可信值(如自定义常量,而非用户输入)。
  • 排查列名大小写与引号问题:若创建表时列名用双引号包裹(如"DrugName"),SQLite会区分大小写,查询时需给列名加双引号:
    cur.execute(f"SELECT * FROM finale WHERE \"{slot_name}\" = ?", (slot_value,))
    
  • 验证数据库连接正确性:确认ubats.db是图片对应的数据库文件,避免连接到错误的数据库实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 22:45:34