0

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)
2
  • prefer using prepared statements like in the below answer, rather than usin concatenation which might cause vulnerability to SQL injection attacks. Commented Dec 22, 2021 at 12:44
  • What do you want to select with LIKE ? All fruits where content is exactly equal to 'apple' or where it contains the keyword %apple% matching also 'pineapple' ? Why not WHERE content IN ('apple', 'pear") ? Commented Dec 22, 2021 at 12:58

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

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.