0

我正在尝试使用映射将值传递到 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])

基本上,我试图获取一个查询以选择水果作为 type1,然后选择项目作为苹果和橙色(以第一次迭代为例)。

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

4

2 回答 2

1

为什么不在调用 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)
于 2021-03-03T19:25:43.310 回答
0

Well your SQL string has three question marks but you only pass in the type and the single list.

So what you need to do is access the individual items of the list and pass those in as parameters,

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

but note that this assumes that there's two items (or more) in the list, and of course if your list had more than two items, then the extra items would just be ignored.

Also the SQL statement seems weird. It would select a record only if the item is BOTH apple AND orange AT THE SAME TIME. That's obviously impossible.

于 2021-03-03T19:11:06.337 回答