Just_Some_Guy
Just_Some_Guy

Reputation: 330

psycopg2 passing in table name

I have the following query

table = "#temp_table"
cursor.execute("""select * from %s as a """, (table))

I keep getting a syntax error at the from stement. Why will this not work?

Upvotes: 2

Views: 2306

Answers (1)

Maciej Gol
Maciej Gol

Reputation: 15854

You are receiving this error because the arguments passed into the second argument, (table) (which really should be (table,)), are escaped in the SQL statement that is run.

In this example, the select * from %s as a is transformed into select * from '#temp_table' as a which is an error. To correctly insert a table name, you need to format the SQL statement string directly like so:

query = 'select * from "{}" as a'.format(table)
cursor.execute(query)

You should be very careful about what data you insert into the query this way because it's highly susceptible to SQL-injection exploits. Do not use this with untrusted data.

Upvotes: 2

Related Questions