简体   繁体   English

psycopg2 传入表名

[英]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.您收到此错误是因为传递给第二个参数(table) (实际上应该是(table,) )的参数在运行的 SQL 语句中被转义了。

In this example, the select * from %s as a is transformed into select * from '#temp_table' as a which is an error.在此示例中, select * from %s as a转换为select * from '#temp_table' as a ,这是一个错误。 To correctly insert a table name, you need to format the SQL statement string directly like so:要正确插入表名,您需要像这样直接格式化 SQL 语句字符串:

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.您应该非常小心以这种方式将哪些数据插入到查询中,因为它极易受到 SQL 注入攻击。 Do not use this with untrusted data.不要将其用于不受信任的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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