0

I'm having this situation to check whether an account number exists in a row in database. The column can contain a number of account numbers each separated by a comma eg. 00001,00002,00003. eg case:SELECT * FROM finance_collection.member WHERE account_ids LIKE 00001,% OR %,00001 OR %,00001,% OR 00001 For this I wrote an SQL statement as:

account_exists = " SELECT * FROM finance_collection.member WHERE account_ids LIKE %s,% OR %,%s OR %,%s,% OR %s "  

Here %s is the incoming account number , is a comma and % is a multicharacter wildcard.

    try:
    with connection.cursor() as cursor:

        sql = sqls.account_exists
        cursor.execute(sql, (account, account, account, account))
        return True

    except pymysql.Error as error:
    print(error)
    return False

I'm using pymysql to connect and it seems the query isn't working. I tried various combinations like surrounding %s,% with ' ' and others but none of them worked. Can you show me a light here?

6
  • "the query isn't working." can you be more specific? error? wrong results? what? remove the try/except to find out the whole traceback. Commented May 1, 2018 at 5:30
  • have you tried escape '\' the % character? Commented May 1, 2018 at 5:33
  • Did you try to run this query directly in the DB? ;) Commented May 1, 2018 at 5:35
  • 1
    Double your % to escape them. Commented May 1, 2018 at 5:38
  • @AndrewPaxson that won't work. It'll raise TypeError: not enough arguments for format string Commented May 1, 2018 at 5:40

1 Answer 1

1

Escape the % with another % (yes this doesn't make much sense but it is what it is):

x = "a=%sx%%2C" % ('text')
x
>>> 'a=textx%2C'
Sign up to request clarification or add additional context in comments.

Comments

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.