5

I have this SQL query:

sql = "select * from table where date in {dl}"

where dl is a tuple of dates. I can do the query by doing string.format(dl=...) then using read_sql_query in pandas, but I read that this could lead to SQL injection and so isn't safe.

However, there doesn't seem to be a good alernative in SQLAlchemy. You can't seem to pass a list to the params using text(), and converting the list into a string first leads to an error. I see that you can iterate over the list and pass the parameters one by one, but why would anyone want to do that?

Would cleaning up the variable (removing quotes, semicolons, etc) help reduce the risk of SQL injection? Not being able to use a raw SQL string sounds like a terrible prospect.

1 Answer 1

7

You can use .bindparams() to bind parameters to values in your text() construct:

sql = text("select * from table where date in :dl").bindparams(dl=...)

Note that the value you pass to dl has to be a tuple to be rendered correctly.

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

3 Comments

Thanks, this works for a tuple of dates. What if the param is a string? Would bindparams escape this properly and avoid the possibility of a SQL injection?
@tangfucius It's never actually escaped -- it's passed directly into the DBAPI execute() as parameters, separate from the SQL, which the database handles.
Great! That makes it totally safe then.

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.