-2

Here is a part of my script :

sql1 = """
                    SELECT distinct th.name, 'MMS' as Status
                    FROM t1 
                    JOIN t2 on t1.id = t2.tid
                    WHERE t2.station= 'MatS'
                    AND t1.name IN ({listthinglist})
        """.format(listthinglist=', '.join("'" + item + "'" for item in list_of_things))
    cur.execute(sql1)

The list_of_things contains 22016 items and I am unable to run this query in python. Is there an alternative to run queries like this in python.

4
  • 2
    What does "unable to run" mean? Are you seeing an error message? Commented Jun 1, 2018 at 22:26
  • 1
    You could do batches and add the results every iteration Commented Jun 1, 2018 at 22:28
  • 1
    @PatrickHaugh my guess is the size of the query string is larger than the DBMS can handle. Commented Jun 1, 2018 at 22:31
  • Create a temporary table and use that: stackoverflow.com/a/48392389/2681632. And don't use string formatting for passing values to SQL queries. Commented Jun 1, 2018 at 22:56

1 Answer 1

0

Please do not use format for this. The execute function accepts a 'parameters' argument that you would pass your list to. You can modify it like so:

sql1 = """
  SELECT distinct th.name, 'MMS' as Status
  FROM t1 
  JOIN t2 on t1.id = t2.tid
  WHERE t2.station= 'MatS'
  AND t1.name IN (%s)
"""
cur.execute(sql1, (list_of_things,))
Sign up to request clarification or add additional context in comments.

8 Comments

Won't this still execute an insanely sized query string?
Try it and if it produces and error, post the exact error message.
That's not my job, that's either yours, or OP's. I asked you since you posted the answer, you should know what it does.
I know what it does, but cant possibly know how it runs on OPs particular server.
Not refuting that, but you'd know whether it inserts the parameters into the string or executes them in some other way, wouldn't you? That's what I was asking. I'm not an sql guy, I'm a pandas guy.
|

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.