-->

How to escape % in a query using python's sqla

2020-02-24 12:53发布

问题:

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?

回答1:

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%")