使用psycopg2撰写动态SQL字符串

问题描述:

我在Python(2.7.10)中使用psycopg2来连接到postgresql数据库。关于动态SQL语句组成的文档非常清楚:使用psycopg2撰写动态SQL字符串

从来没有,从来没有,从不使用Python字符串连接(+)或字符串参数插值(%)将变量传递给SQL查询字符串。甚至没有枪支。

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 import sql 

SQL = sql.SQL("SELECT * FROM {}").format(sql.Identifier(".".join([schema, table]))) 
print SQL.as_string(C)  
cur.execute(SQL) 
+0

我错过了join()的想法。 – Dschoni