29

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?

2 Answers 2

45

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%")
Sign up to request clarification or add additional context in comments.

4 Comments

Hi~, How to use it with sqlalchemy orm?
@DachuanZhao session.query.filter(table.string.like('_stringStart%'))
@bfontaine Why should it escape the percent? It does exactly the same thing as the example in the answer. ORM already uses bound parameters. The internal sqlalchemy code does not (or no longer) use the query with a '%' string expansion, which was the original error.
@wolfmanx sorry, I misunterstood the question. I thought it was about escaping % so that *SQL wouldn’t interpret it while it was about escaping for Python itself. I deleted my comment.
0

Another way to implement bound parameters:

from sqlalchemy import text

connection.execute(
    text("select id_number from Table where string like :string limit 1").\
    bindparams(string="_stringStart%")
)

or even typed strictly:

from sqlalchemy import bindparam, String, text

connection.execute(
    text("select id_number from Table where string like :string limit 1").\
    bindparams(bindparam("string", type_=String)),
    {"string"="_stringStart%"}
)

Bear in mind that text() construct is deprecated sine SQLAlchemy 1.4 and will be removed in SQLAlchemy 2.0.

1 Comment

I can't find anything saying text() is deprecated. No deprecation warning in the API docs (docs.sqlalchemy.org/en/14/core/…) and it's still in tutorial (docs.sqlalchemy.org/en/14/core/tutorial.html#sqlexpression-text)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.