PyODBC query with multiple wildcard parameters

I am trying to use the following SQL query through pyodbc:

SELECT * FROM table WHERE variable1 LIKE '%test1%' and variable2 LIKE '%test2%'

I found a way to do it for a single parameters on the link

filter = 'test1'
sql = "SELECT * FROM table WHERE variable1 LIKE ?"
param = f'%{filter}%'
rows = cursor.execute(sql, param).fetchall()

Can you please help me to write the SQL query on pyodbc?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You may go with the same approach of your example, just with 2 parameters:

filter1 = 'test1'
filter2 = 'test2'
sql = "SELECT * FROM table WHERE variable1 LIKE ? AND variable2 LIKE ?"
params = (f'%{filter1}%',f'%{filter2}%') 
rows = cursor.execute(sql, params).fetchall()

Or simplify it a bit:

filter1 = 'test1'
filter2 = 'test2'
sql = f"SELECT * FROM table WHERE variable1 LIKE %{filter1}%? AND variable2 LIKE %{filter2}%?"
rows = cursor.execute(sql).fetchall()

Method 2

Have you tried this? It’s related to named parameters binding and should support any arbitrary number or params.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x