问题
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)
回答1:
I think it should be
cursor.execute("""Select t1, t2, t3, t4 from database where t1 in ('1', '2', '3', '4')""")
回答2:
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)) # ?,?,?,?
sql = f"SELECT * FROM tablename WHERE t1 IN ({qmarks})" # SELECT * FROM tablename WHERE t1 IN (?,?,?,?)
example = crsr.execute(sql, X).fetchall()
来源:https://stackoverflow.com/questions/54205054/passing-a-python-list-through-a-sql-statement-on-a-loop