0

If want to search for a description which contains the words "hex" and "nut" I would use a query like this:

cursor.execute("SELECT description FROM %s WHERE description LIKE %?% AND
    description LIKE %?%" % table_name , ["hex", "nut" ])

But what if the user wants to now search for a description that contains 5 terms?

Previously in pure sql I had written something like this to generate my results:

base = """
SELECT description FROM {0}
WHERE
""".format(table_name)
command = base
# Adding "AND" for each term
for i in range(len(search_terms)):
    # Last portion of the SQL query
    if i == (len(search_terms) - 1):
        command += " description LIKE '%{0}%'".format(search_terms[i])
    else:
        command += " description LIKE '%{0}%' AND ".format(search_terms[i])
command = command.replace("\n", "")
cursor.execute(command)

However I was hoping there was a better way of doing this with sqlite and sql queries. I know that I could load all the data onto memory and use pure Python to achieve what I want but I want to SQL. So is there an elegant and safe way of doing this?

I'm new to stackoverflow and SQL so let me know if I asked my question wrong.

1 Answer 1

0

Consider a list comprehension with Pythons's str.join:

table_name = 'prices'                                    # EXAMPLE
command = """ SELECT description FROM {0} WHERE """.format(table_name)

search_terms = ['hex', 'nut', 'screw', 'bolt', 'nail']   # EXAMPLE
where = ' AND '.join(["description LIKE '%?%'" for i in search_terms])

command = command + where    
print(command)
#  SELECT description FROM prices WHERE description LIKE %?% AND description LIKE %?%
#         AND description LIKE %?% AND description LIKE %?% AND description LIKE %?% 

cursor.execute(command, search_terms)                    # PARAMETERIZED QUERY
Sign up to request clarification or add additional context in comments.

2 Comments

Tried this answer, it looks really slick but for some reason I get `sqlite3.OperationalError: near "%": syntax error
Whoops! Forgot the single quotes across literal containing the wildcard operators. See edit. I quickly grabbed your first cursor.execute() code believing it was fully valid.

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.