Skip to content
Advertisement

Iterating through a list Python SQL

I’m trying to search a database, by iterating through a list of search values. I’m almost there as this works for integers but not strings. The code below won’t work, but if I replace the list values with numbers it does:

mycursor = mydb.cursor()

lst = []

select_query = "SELECT * FROM fruit WHERE content LIKE "
ids = ["apple", "pear"]

for x in ids:
    var = select_query + str(x)
    
    mycursor.execute(var)
    lst.extend(mycursor.fetchall())

print(lst)

Advertisement

Answer

It’s because you have to enclose strings in quotation marks in SQL. So for example

SELECT * FROM fruit WHERE content LIKE 'pears'

will work, and it will only work with the single quotations around “pears”. Even better, type conversion can (and should) be done automatically with psycopg2:

select_query = "SELECT * FROM fruit WHERE content LIKE %s"
...
mycursor.execute(select_query, (x,))

https://www.psycopg.org/docs/usage.html#strings-adaptation

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement