使用 psycopg2 编写动态 SQL 字符串

Dsc*_*oni 6 python postgresql sql-injection psycopg2

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

从不,从不,永远不要使用 Python 字符串连接 (+) 或字符串参数插值 (%) 将变量传递给 SQL 查询字符串。甚至不是在枪口下。

psycopg22.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
Run Code Online (Sandbox Code Playgroud)

Eug*_*ash 11

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

from psycopg2 import sql

query = sql.SQL("SELECT * FROM {}.{}").format(*map(sql.Identifier, (schema, table)))
print query.as_string(conn)
cur.execute(query)
Run Code Online (Sandbox Code Playgroud)

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

query = sql.SQL("SELECT * FROM {}").format(sql.Identifier(schema, table))
Run Code Online (Sandbox Code Playgroud)