I want to pass dynamic parameter to the LIKE query using Fast API (Python) coming from the query parameter. I have tried a lot of ways but I don't know what I am doing wrong.
The query I need to use is :
SELECT Time, table_id, Text FROM tablename WHERE Text LIKE '%text%'
The python code for getting query parameter is :
def get_result(text : str):
con = connection.connect()
statement = 'SELECT Time, table_id, Text FROM tablename WHERE Text LIKE '%text%''
How will I pass the dynamic text parameter in this query because this gives the error saying "TypeError: not all arguments converted during string formatting"?
CodePudding user response:
You cannot nest single quotes. Also, it's clearer to use a f-string for string formatting here. Try:
statement = f"SELECT Time, table_id, Text FROM tablename WHERE Text LIKE '%{text}%'"
CodePudding user response:
NEVER substitute values directly in to a SQL string like that. EVER. Use parameterised queries / bind variables.
For example, depending on the driver/library you're using, you may be able to use...
con = connection.connect()
cur = con.cursor()
cur.execute("SELECT Time, table_id, Text FROM tablename WHERE Text LIKE %s", ('%' text '%',))