用 psycopg2 组成动态 SQL 字符串

Compose dynamic SQL string with psycopg2

我在 python (2.7.10) 中使用 psycopg2 连接到 postgresql 数据库。文档非常清楚动态 SQL 语句的组成:

Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.

psycopg2 2.7 版中,有新的 sql 模块可以安全地防止 SQL 注入来执行此字符串组合。尽管如此,我还是不明白如何正确构建如下语句:

import psycopg2 as ps

C = psycopg.connect(host='my_host', port=Port, database='My_DB')
cur = C.cursor()
schema = 'some_schema'
table = 'some_table'
SQL = cur.execute("SELECT * FROM "+schema+"."+table+";") # This is horribly wrong
SQL = cur.execute("SELECT * FROM some_schema.some_table;") # That's what the result should be

您可以使用 psycopg2.sql.Identifier 将标识符插入查询,例如:

from psycopg2.sql import Identifier, SQL

query = SQL('SELECT * FROM {}.{}').format(*map(Identifier, (schema, table)))
print(query.as_string(conn))
cur.execute(query)

根据链接的文档页面,在 psycopg2 v2.8+ 中,您还可以将多个字符串传递给 Identifier 以表示限定名称,即以点分隔的标识符序列:

query = SQL('SELECT * FROM {}').format(Identifier(schema, table))