3

I have a tuple like as shown below

vilist = (1,2,3,4)

I am trying to use them in Psycopg2 query like as shown below

sql = "select * from temp.table1 where ids in {}"
cur.execute(sql,vilist)

Which should parse a SQL string like

SELECT * FROM temp.table1 WHERE ids IDS (1,2,3,4);

However, I get an error like as shown below

SyntaxError                               Traceback (most recent call last)
<ipython-input-91-64f840fa2abe> in <module>
      1 sql = "select * from temp.table1 where ids in {}"
----> 2 cur.execute(sql,vilist)

SyntaxError: syntax error at or near "{"
LINE 1: ...rom temp.table1 where ids in {}

Can help me resolve this error please.

1
  • klin - the example shows for single value but I wnt to pass a tuple containing multiple values. Commented Sep 20, 2021 at 12:14

1 Answer 1

2

Use SQL string composition to pass identifiers or literals to a query text.

import psycopg2
import psycopg2.sql as sql
# ...

vilist = (1,2,3,4)
query = sql.SQL("select * from temp.table1 where ids in {}").format(sql.Literal(vilist))
cur.execute(query)
Sign up to request clarification or add additional context in comments.

3 Comments

It results in error like AttributeError: 'str' object has no attribute 'SQL' which am trying to find online as t what is causing this error
I tried both sql.sql and sql.SQL but it doesn't work..
You have a string variable sql - note, that I have changed it to query. Delete sql variable from the script.

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.