Search code examples
pythonreplacevariable-expansion

How to search for martial matches when mysql query contains a placeholder in python?


Query 1:

"SELECT name FROM mytable WHERE name LIKE '%e%'";

This query will look for all names that contain the letter ‘e’.

Query 2:

"SELECT name FROM mytable WHERE name LIKE '%s'" % search_name;

This query will look for all names that contain match search_name exactly.

What I want to know is if there is a way to query for a partial match like in query 1 while using the placeholder in query 2?

I have tried something like:

"SELECT name FROM mytable WHERE name LIKE %'%s'%" % search_name; <- didn’t work; "SELECT name FROM mytable WHERE name LIKE '%%s%'" % search_name; <- also didn’t work;


Solution

  • Either use a different way of formatting the string inside your query string like

    SELECT name FROM mytable WHERE name LIKE '%" + search_name + "%'"
    

    or f-Strings.

    Or you could add more % and escape it with a slash so it gets put into the string normally.

    \%%s\%