如何从 python 中的循环将参数映射应用于 read_sql

How to apply map of parameters to read_sql from loop in python

我正在尝试使用映射将值传递到 read_sql 语句中。这是我尝试过的:

inventory = {
    'fruit': ['apple', 'orange'],
    'veggies': ['onion', 'cucumber'],
    }

for type, items in inventory.items():
    with pyodbc.connect('DSN=DB_CONN') as conn:
        df_t_minus_1 = pd.read_sql("SELECT * FROM temp_table where type1 = ? and item = ? and item = ?", conn, params=[type, description])

基本上,我正在尝试查询 select fruit as type1 然后 item as apple 和 orange(以第一次迭代为例)。

但是,我一直收到一条错误消息,说它需要 3 个参数,但我传递了 2 个。我假设这是因为它只消耗列表中的 1 个项目。我想弄清楚如何将列表传递给后两个?在我的 sql 声明中。感谢您的帮助!

嗯,你的 SQL 字符串有三个问号,但你只传入了类型和单个列表。

所以您需要做的是访问列表中的各个项目并将它们作为参数传递,

params = [type, description[0], description[1]]

但请注意,这假设列表中有两项(或更多),当然如果您的列表超过两项,那么多余的项目将被忽略。

而且 SQL 语句看起来很奇怪。只有当该项目同时是苹果和橙子时,它才会 select 一条记录。这显然是不可能的。

为什么不在调用 read_sql 之前格式化并允许 in_select 查询中的多个项目:

inventory = {
    "fruit": ["apple", "orange"],
    "veggies": ["onion", "cucumber"],
}

sql_str = (
    "SELECT * FROM temp_table where type1 = '{category}' "
    "and item in ({items})"
)

for category, items in inventory.items():
    in_select = "', '".join([item for item in items])
    in_select = f"'{in_select}'"
    sql = sql_str.format(category=category, items=in_select)

    with pyodbc.connect("DSN=DB_CONN") as conn:
        df_t_minus_1 = pd.read_sql(sql, conn)