0

How to pattern match "LIKE" and escape special character with the below Python code? I'm getting errors with special characters.

"parameter" values are "1.1", "1.2","1.3"

cr.execute("select sequence from account_stock_info "
"where sequence like '%s.%' "
"order by sequence ",
(tuple(parameter)))

Original query on PGADMIN was:

select sequence from account_stock_info
where sequence like '1.1.%'
order by sequence

Answer:"1.1.1", "1.1.1.03", "1.1.2","1.1.2.04","1.1.3"

Please help with Python pattern match.

1 Answer 1

1

First error is using tuple function with string parameter:

>>> tuple('1.1')
('1', '.', '1')

you can pass tuple explicitly: (parameter,) or use dict to pass parameters.

To pass percent sign to LIKE statement you can add additional percent sign in your query:

parameter = "1.1"
cr.execute("select sequence from account_stock_info "
           "where sequence like '%s.%%' "
           "order by sequence ",
           (parameter,))

or pass it in parameter (quotes can be deleted here):

parameter = "1.1.%"
# ...
"where sequence like %s "
Sign up to request clarification or add additional context in comments.

3 Comments

Do you have more complete sql query? I still have problem with passing parameters in Like statement?
I got error. My code: parameter = "1.1.%" cr.execute("select id,name,sequence from account_stock_info " "where sequence like %s " "order by sequence ", (parameter,)) Error: No operator matches the given name and argument type(s). You might need to add explicit type casts. , in query select id,name,sequence from account_cash_move_type where sequence like %s order by sequence
I got error. It seems "sequence" is reserved word in Postgre. How to use sequence column now?

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.