简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM