Reputation: 3
I'm searching an SQL table for customers who's name starts with my input and i have problem writing the "Starting With" logic, it works fine when its WHERE ? =. i'm using pyodbc and using driver ODBC Driver 17 for SQL Server
i've seen alot of answers on similar problems but they always refer to using the code %s, and that does not work when i try it
I've tried many different ways of writing LIKE '%' but i cannot find any examples of this
my current code is:
cursor.execute("select CustomerName, CustomerNum From customer WHERE Company = ? AND CustomerName = ?", Company, CustomerName)
result = cursor.fetchall()
for row in result:
print (row)
CustomerName var set to "Mic" and the the result should be:
Microsoft
Micro systems
etc..
Thanks you
Upvotes: 0
Views: 418
Reputation: 781503
You need to concatenate the parameter with the %
wildcard. In MySQL you use the CONCAT()
function, in SQL-Server you use the +
operator.
Also, the parameters that fill in the placeholders should be in a tuple, not separate arguments to cursor.execute()
.
MySQL:
cursor.execute("select CustomerName, CustomerNum From customer WHERE Company = ? AND CustomerName LIKE CONCAT(?, '%')", (Company, CustomerName))
SQL-Server:
cursor.execute("select CustomerName, CustomerNum From customer WHERE Company = ? AND CustomerName ? + '%'", (Company, CustomerName))
Upvotes: 3