Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中应用参数映射从循环中读取sql_Python_Read Sql - Fatal编程技术网

如何在python中应用参数映射从循环中读取sql

如何在python中应用参数映射从循环中读取sql,python,read-sql,Python,Read Sql,我试图使用映射将值传递到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(&q

我试图使用映射将值传递到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,然后将项目选择为apple和orange(在第一次迭代中作为示例)


然而,我不断得到一个错误,说它需要3个参数,但我传递了2个。我假设这是因为它只消耗列表中的一项。我想知道如何将列表传递给后两个?在我的sql语句中。谢谢你的帮助

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

因此,您需要访问列表中的各个项目,并将它们作为参数传入

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

但是请注意,这假设列表中有两个(或更多)项,当然,如果列表中有两个以上的项,那么多余的项将被忽略


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

为什么不在调用read\u sql之前格式化,并在in\u 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)