Search code examples
pythonmysqlwildcardsql-like

MySql Query in Python LIKE with Wildcard


I have seen this question around but the answer that is usually given, does not work with me. I am trying to do a simple query

query_pre_company = "SELECT `name` FROM `seta`.`companies` WHERE `companies`.`name` LIKE SOUNDEX(%s) OR(`companies`.`name` LIKE %s)"
name = sheet.cell(2,2).value #from an excel sheet
name_check='%'+name+'%'
rows_count=cursor.execute(query_pre_company,[name_check])

the result is the error

  ```query = query % tuple([db.literal(item) for item in args])
  TypeError: not all arguments converted during string formatting```

I also tried

rows_count=cursor.execute(query_pre_company,(name_check,))

and a million of other different variations including sticking '%%s%' directly in the query and others

Please help Thanks


Solution

  • Since you have two placeholders, you need to pass two parameters. The parameter for SOUNDEX() should be the name without the wildcards added.

    You're also not using SOUNDEX() correctly. It doesn't return a lIKE pattern, it returns a code string. You need to call it on the column as well and compare them.

    query_pre_company = """SELECT `name` 
                        FROM `seta`.`companies` 
                        WHERE SOUNDEX(`companies`.`name`) = SOUNDEX(%s) 
                        OR `companies`.`name` LIKE %s"""
    name = sheet.cell(2,2).value #from an excel sheet
    name_check='%'+name+'%'
    rows_count=cursor.execute(query_pre_company,[name, name_check])