user713713 user713713 - 11 months ago 107
MySQL Question

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

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?

Answer Source

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

from sqlalchemy import text

    text("select * from table where "
         "string like :string limit 1"),