简体   繁体   中英

Escape a '%' in a mySQL query being executed via python with LIKE and % wildcards

I'm trying to match a string with a '%' in it through a LIKE operator but this gives me a python TypeError due to the formatting getting messed up.

Example:

SELECT *
FROM table
WHERE name LIKE "%exam\%ple%"

In python the query would look like this due to escaping the LIKE wildcards

match = "%%exam\\%ple%%"

query = """
SELECT *
FROM table
WHERE name LIKE "%s"
""" % (match)

Yet this still throws me the same error.

How would I write the query in python to search table where name matches all instances of "exam%ple" ?

You don't need to escape the % instances in the string that is to the right of the % in the generation of the query so:

match = r"%exam\%ple%"  # Use r string to avoid having to double \s
query = """
SELECT *
FROM table
WHERE name LIKE "%s"
""" % (match)
print(query)  # as a check

Results in:

SELECT *
FROM table 
WHERE name LIKE "%exam\%ple%"

Also note that you can effectively escape, ie make literal, % characters by doubling them, ie %d = insert number but %%d = insert "%d" however you will need to double for each % operation that you are performing.

A better alternative would be to use the string format command which is available in both python 3.4+ any python 2.7. This uses {} as a marker for insertion points, (it is classed as a mini-language), and will not touch your % signs.

In [2]: "{} == {}".format(1,2)
Out[2]: '1 == 2'

In [3]: match = r"%exam\%ple%"  # Use r string to avoid having to double \s

In [4]: query = """
   ...: SELECT *
   ...: FROM table
   ...: WHERE name LIKE "{}"
   ...: """.format(match)

In [5]: print(query)

SELECT *
FROM table
WHERE name LIKE "%exam\%ple%"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM