0

I've prepared a list in Python, and would like to use that list to filter the items I query from a SQL database.

I have a query like this:

sql_query = "
    SELECT item
    FROM database
    WHERE item IN (*list*) "

And want to place a list that I prepared earlier in the script in the place of list. How would I do this? %s and %d don't seem to do it.

1 Answer 1

3

Without knowing the SQL library being used (which could make this easier), the safest way would be to use a %s (or ?, or other appropriate parameter marker) for each item in the list, and pass the list in the parameters. Example:

sql_query = """
    SELECT item
    FROM database -- This is actually a table.
    WHERE item IN ({})
""".format(','.join(['?'] * len(items)))

cursor.execute(sql_query, items)

This will create a query like:

SELECT item
FROM database
WHERE item IN (?,?,...)

Which is still safe from SQL injection. If items is empty, this will fail with a syntax error because item IN () is not valid in any SQL database that I'm aware of.

Sign up to request clarification or add additional context in comments.

9 Comments

Doesn't it need to be ? and not %s?
What library are you using? Because it depends entirely on the SQL library you're using as to whether you use ?, %s, or some other marker.
Ahh, I usually use pyodbc with ? bind variables.
Did you mean to put ' * len(items)' inside the join function and outside the one element list?
@goldisfine Yep, that's exactly what I meant so that you get len(items) many ?s joined by ,s.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.