Home > Software design >  PyODBC query with multiple wildcard parameters
PyODBC query with multiple wildcard parameters

Time:04-30

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?

CodePudding user response:

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()

CodePudding user response:

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

  • Related