1

I am trying to figure out how to pass a list as a parameters through a where statement in SQL, I can not program what I am looking for, but below is what I am looking for.

This is what I would do for one parameter.... x = 1 sql = """Select t1,t2,t3,t4 from database where t1= ? """ cur.execute(sql,x)

Example of what I need

X = [1,2,3,4]
Select t1,t2,t3,t4 from database where t1= 1
Select t1,t2,t3,t4 from database where t1= 2
Select t1,t2,t3,t4 from database where t1= 3
Select t1,t2,t3,t4 from database where t1= 4

Example of what I am trying that isn't working....

X = [1,2,3,4]
sql = """Select Select t1,t2,t3,t4 from database where t1= ? """
example=[]
i = 0
for item in X:
    while i < len(x)
        row = cur.execute(sql,item)
        i +=1
        example.append(row)
6
  • Are you aware about cur.executemany? Commented Jan 15, 2019 at 18:45
  • You have "Select Select"... get rid of one of them. Commented Jan 15, 2019 at 18:47
  • You also need to clarify "not working" and the while loop with the i counter is confusing me. Commented Jan 15, 2019 at 18:49
  • Can't test; cur.execute("SELECT t1, t2, t3, t4 FROM database WHERE t1 IN ({})".format(', '.join(['?' for item in X])), X) Commented Jan 15, 2019 at 18:52
  • What error exactly do you get? "not working" is a bit too much generic. Commented Jan 15, 2019 at 19:20

2 Answers 2

1

If all you're doing is looping through a list of IDs and appending a row to a list named example then you can just build a dynamic IN clause and retrieve the rows all at once:

x = [1, 2, 3, 4]
qmarks = ','.join('?' * len(x))  
print(qmarks)  # ?,?,?,?
sql = f"SELECT * FROM tablename WHERE t1 IN ({qmarks})"  
print(sql)  # SELECT * FROM tablename WHERE t1 IN (?,?,?,?)
example = crsr.execute(sql, x).fetchall()
Sign up to request clarification or add additional context in comments.

Comments

0

I think it should be cursor.execute("""Select t1, t2, t3, t4 from database where t1 in ('1', '2', '3', '4')""")

Comments

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.