[FIXED] SQL prepared statement with LIKE '%?%'

Issue

I'm implementing a search function into my application, and I would like it to be 'smart'. The search is made into an SQL-query.

I would like the following functionality: searching for 'litago' will show 'litago 500ml', litago 375ml', 'Small litago', 'superlitago223'

that is 'ANY_STRING_HERE'+'litago'+'ANY_STRING_HERE'

I want to do this in the SQL querylike this:

query = 'SELECT * FROM varer WHERE navn LIKE '%?%' '

? is user input, litago is just an example

However, this gives a syntax error. Is there a way of doing it like this?

Edit: Using python 3.6.4, here is the relevant code

From rogerbinns github:

There are two ways of supplying data to a query. The really bad way is to compose a string:

sql="insert into example values('%s', %d)" % ("string", 8390823904)
cursor.execute(sql)

If there were any single quotes in string then you would have invalid syntax. Additionally this is how SQL injection attacks happen. Instead you should use bindings:

sql="insert into example values(?, ?)"
cursor.execute(sql, ("string", 8390823904))

Solution

You can't use single quotes inside a string delimited by single quotes without escaping them, however you can inside a double quote delimited string. Something like

query = "SELECT * FROM varer WHERE navn LIKE '%?%' "

should solve your problem.



Answered By - Aran K
Answer Checked By - Mildred Charles (sql.easybugfix Admin)

Related Posts

Post a Comment