1

I have a list called people2 like so:

['xloS4ooQOT',
 '3s4LyNyHs3',
 'NRL6zNePCT',
 '7hkLogfk8T',
 '5JcUkJ8FLO',
 'LZ6DMUfnEA',
 'CmBaomzMXC',
 'M5OPb0yf09',
 'CqG2XYGPxk']

I am trying to use it as the basis for a postgres query via the psycopg2 module:

query = "SELECT userid, measurementvalue FROM db WHERE userid IN (%s)"
cur.execute(query, people2[1:5])

That produces the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-30-5825c6e2c3fa> in <module>()
      1 query = "SELECT userid, measurementvalue, displaydate, datatype FROM parse_dataobject WHERE userid IN (%s)"
----> 2 cur.execute(query, people2[1:5])
      3 for r in rows[:5]:
      4     print(r)

TypeError: not all arguments converted during string formatting

I also tried removing the parentheses, but this leads to the same result:

query = "SELECT userid, measurementvalue, displaydate, datatype FROM parse_dataobject WHERE userid IN %s"

I am simply trying to follow the docs + previous posts (Python List to PostgreSQL Array), but I seem to be missing something. What is wrong with what I'm doing?

2 Answers 2

2

From psycopg2 doc on Lists adaptation, your code should look like this:

query = "SELECT userid, measurementvalue FROM db WHERE userid = any(%s)"
cur.execute(query, (people2[1:5],))
0

Python tuples are converted to sql lists in psycopg2:

cur.mogrify("SELECT * FROM table WHERE column IN %s;", ((1,2,3),))

would output

SELECT * FROM table WHERE column IN (1,2,3);

you need convert the list in tuple and after use this tuple, for example:

people2 = ['xloS4ooQOT', '3s4LyNyHs3', 'NRL6zNePCT', '7hkLogfk8T', '5JcUkJ8FLO', 'LZ6DMUfnEA', 'CmBaomzMXC', 'M5OPb0yf09', 'CqG2XYGPxk']

query = "SELECT userid, measurementvalue FROM db WHERE userid IN %s" cur.execute(query, tuple(people2[1:5]))

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.