Search code examples
pythonsqlsql-serverpymssql

how to use LIKE and % with pymssql on an undetermined number of parameters?


I am using pymssql to connect to a database. That database has a table that has a column (let's call it col) on witch all the strings are 64 chars long. (ex: "John "). Now i want to find John in the database. i tried using LIKE. When i hardcode the name it works perfectly :

cursor.execute("SELECT * FROM table WHERE col LIKE 'John%' ") // gives perfect results

But when i try it using %s this seems to match nothing.

cursor.execute("SELECT * FROM table WHERE col LIKE '%s%' ",(0,"John")) // gives Nothing
cursor.execute("SELECT * FROM table WHERE col LIKE '%s%' ",{0:"John"}) // gives SQL "Incorrect syntax" error
cursor.execute("SELECT * FROM table WHERE col LIKE '%s%' " % {0:"John"}) // gives unsupported format error

If i wanted to match only one column this would have worked :

cursor.execute("SELECT * FROM table WHERE col LIKE '%s%' ", "John") // gives all Johns

But I want to match on an undetermined number of columns. Is there a way to have a look a what the final query would look like so I can try debugging it myself. Or else do you know how to use many parameters. after looking here it seems I should use an array of tuples but i can't find a way to make it work.

Thank you in advance


Solution

  • Try this:

    cursor.execute("SELECT * FROM table WHERE col LIKE %s ", "John%")