Home » Mysql » How to escape % in a query using python's sqlalchemy's execute() and pymysql?

How to escape % in a query using python's sqlalchemy's execute() and pymysql?

Posted by: admin November 29, 2017 Leave a comment

Questions:

My query is:

result = connection.execute(
         "select id_number from Table where string like '_stringStart%' limit 1;")

gives the error:

query = query % escaped_args
TypeError: not enough arguments for format string

A quick google said to use %% instead of % but that doesn’t work either. How do I escape the % or is there another way to query for a string that starts with a random letter then a certain sequence?

Answers:

Since this is a literal string, you’re better off using a bound parameter here (illustrated using text()):

from sqlalchemy import text

connection.execute(
    text("select * from table where "
         "string like :string limit 1"), 
    string="_stringStart%")

Questions:
Answers:

Escape it with a backslash \

I use it when I perform LIKE queries:

query_wildcard = "%{0}%".format(query.replace("%", "\%"))

For searches where query is 100%, query_wildcard then contains %100\%% so it actually searches for 100%

Maybe it’s something to implement in your code?