0

I'm trying to safely build an SQL query from a given string. The string can contain whitespaces.

string = "chair"

query = """SELECT *
             FROM albums
             WHERE title LIKE %s"""
values = ('%' + string + '%',)
cur.execute(query,values)
# >> SELECT * FROM albums WHERE title LIKE '%chair%'

But I can't figure out how to safely extend this to search for multiple words with the AND operator.

string = "big blue chair"
# >> SELECT * FROM albums WHERE title LIKE '%big%' AND
#                               title LIKE '%blue%' AND
#                               title LIKE '%chair%'

(I know this is what FULLTEXT searches are for, etc ... but this is for a very small dataset and is fast enough.)

1
  • What's unsafe about doing the obvious: values = ["%{}%".format(val) for val in string.split()]? Not being snarky, I'm just not sure what your concern is. Commented Jul 11, 2014 at 15:06

2 Answers 2

3

If you want to dynamically expand both the query and values based on string, you can do it like this:

string = "big blue chair"
query = "SELECT * FROM albums WHERE title LIKE %s"
values = ["%{}%".format(val) for val in string.split()]
for _ in values[1:]:  # iterate over len(values) - 1
    query += " AND title LIKE %s"
print(query)
print(values)

Output:

SELECT * FROM albums WHERE title LIKE %s AND title LIKE %s AND title LIKE %s
['%big%', '%blue%', '%chair%']
Sign up to request clarification or add additional context in comments.

Comments

0

Split your string on spaces.

Then:

cursor.execute("SELECT * FROM albums WHERE title LIKE %s AND title LIKE %s AND title LIKE %s", (var1 , var2, var3))

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.