I am trying to use string formatting with SQL. But while passing in variables, these are inserted with quotes and break the syntax.
Example
Here I am trying to pass in the table name to the function.
def see_results(cur, table):
print("complete")
cur.execute(''' SELECT * from %s ''', (table,))
results = cur.fetchall()
print(results)
Issue
If I pass "temp_yellow_pages" as argument the resulting query is: ''' SELECT * from "temp_yellow_pages" '''.
This breaks.
I can't think of a way to assign anything to the variable table without using "'s as query = temp_yellow_pages would break as well.
f"SELECT * from {table}"available.tableto betable = "employee -- drop table employee"or some other "here be dragons" example of sql based on string concat?psycopg2, for example, providescur.execute(psycopg2.sql.SQL("select * from {}").format(sql.Identifier(table))). Note this isn'tstr.format, but aSQL.formatmethod that knows about SQL syntax.