Reputation: 1488
I want to select data from my database where the COLUMN_NAME
value contains a string, an example is below:
SELECT * FROM mytable WHERE LOWER(COLUMN_NAME) LIKE LOWER('%foobar%')
The above SQL statement should select from the table mytable
where COLUMN_NAME
contains foobar
(incase sensitive)
However foobar
was an example and I'm not sure how to implement this in a Python MySQLdb query while escaping the value which will be put instead of foobar
I have tried the following but it seems their syntax is incorrect:
value = "foobar"
cursor.execute("SELECT * FROM mytable WHERE LOWER(COLUMN_NAME) LIKE LOWER('%%s%')", (value,))
value = "foobar"
cursor.execute("SELECT * FROM mytable WHERE LOWER(COLUMN_NAME) LIKE LOWER(%%s%)", (value,))
value = "foobar"
cursor.execute("SELECT * FROM mytable WHERE LOWER(COLUMN_NAME) LIKE LOWER('% %s %')", (value,))
Any help on how to get it working?
Upvotes: 0
Views: 360
Reputation: 3115
Therefor should work.
To be honest, I have not tested this with MySQLdb, but usually you can escape the `%` in format-strings by doubling it.
value = "foobar"
cursor.execute("SELECT * FROM mytable WHERE LOWER(COLUMN_NAME) LIKE LOWER('%%%s%%')", (value,))
UPDATE:
My proposed solution doesn't work, because the query is prepared with mogrify()
which uses literal()
.
literal
always adds the single quotes '
. So the query becomes LOWER('%'foobar'%')
and is invalid.
Please Consider Parfait's solution.
Upvotes: 2
Reputation: 107587
For parameterized queries that use the percent symbol, %
, parameter value should include the wildcards which you can interpolate with F-string:
# VALUE WITH WILDCARDS
value = "foobar"
param = f"%{value}%"
# PREPARED STATEMENT WITHOUT QUOTES
sql = "SELECT * FROM mytable WHERE LOWER(COLUMN_NAME) LIKE LOWER(%s)"
# EXECUTE AND BIND PARAM
cursor.execute(sql, (param,))
Upvotes: 2