Python find a string with single quote symbol in postgresql table

Viewed 217

I need to look up for a string that contains multiple single quotes from my psql table. My current solution is replacing the single quotes with double single quotes like this:

sql_query = f"""SELECT exists (SELECT 1 FROM {table_name} WHERE my_column = '{my_string.replace("'","''")}' LIMIT 1);"""
cursor = connection.cursor()
cursor.execute(sql_query)

Is there a nicer solution for this kind of formatting ?

1 Answers

I solved this by making the query like this

sql_query = f"""SELECT exists (SELECT 1 FROM {table_name} WHERE my_column = %s LIMIT 1);"""
cursor = connection.cursor()
cursor.execute(sql_query, (mystring,))

In this case it formats mystring in such way that it is not executed as sql query and doesn't cause the problems mentioned in the question

Related