pythonread-sql

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


I am trying to use a map to pass in values into a read_sql statement. Here's what I've tried:

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])

Basically, I am trying to get a query to select fruit as type1 then item as apple and orange (in the first iteration as an example).

However, I keep getting an error saying it expects 3 parameters but I am passing 2. I am assuming this is because it only consumes 1 item from the list. I'd like to figure out how to pass the list to the second two ? in my sql statement. Thank you for your help!


Solution

  • why don't just format before call read_sql and allow for multiple items in an in_select query:

    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)