psycopg2 传入 table 名称

psycopg2 passing in table name

我有以下查询

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

我总是在发件人处收到语法错误。为什么这不起作用?

您收到此错误是因为传递到第二个参数 (table)(实际上应该是 (table,))的参数在 SQL 语句中被转义 运行.

在这个例子中,select * from %s as a被转换成select * from '#temp_table' as a,这是一个错误。要正确插入 table 名称,您需要像这样直接格式化 SQL 语句字符串:

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

您应该非常小心以这种方式将哪些数据插入到查询中,因为它很容易受到 SQL 注入攻击。不要将此与不受信任的数据一起使用。