Skip to content
Advertisement

How to automate parameters passed into pandas.read_sql?

I am trying to create a methodology for passing parameters automatically through something like locals(), similarly to how f-strings work.

How it currently works

However, this approach means I cannot copy-paste the SQL into SQL developer or similar, and run it from there. So I would like an approach that makes use of parameters instead.

There seems to be two problems with that

  1. Parameters must be literals, so its not possible to pass along lists
  2. I need to create a dictionary manually, and cannot simply pass something like locals()

How I would like it to work would be something like the example below (which obviously doesn’t work)

EDIT: After testing a bit, maybe I could use a regex to find all instances of :param and replace them with the parameter value, e.g.

It’s just not very pretty, and it introduces issues related to object types. E.g. the string_id should be encapsulated by ', and the date needs to be converted to a string object as well

Final edit: Thanks to perl, I now have a working solution to my problem

Advertisement

Answer

You can use parametrized queries by wrapping the query in sqlalchemy.text and converting lists to tuples. For example:

Output:


For completeness of the example, the following was used as a test table:


Update: Here’s a possible workaround for Oracle to make it work with lists:


Update 2: Here’s the get_query function that works with both strings and numbers (enclosing in quotes strings, but not numbers):

For example:

Output:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement