[英]Pass column name as parameter to PostgreSQL using psycopg2
I'm trying to add columns to a table using psycopg2
我正在尝试使用
psycopg2
将列添加到表中
row1
below is a list of column names to be added to the table. 下面的
row1
是要添加到表中的列名的列表。 I can do it manually but when I try to do it programatically I get an error. 我可以手动进行操作,但是当我尝试以编程方式进行操作时,出现错误。
for c in row1:
cur.execute("ALTER TABLE HHV2PUB ADD COLUMN %s text", (c,))
The error is: 错误是:
cur.execute("ALTER TABLE HHV2PUB ADD COLUMN %s text", (c,))
psycopg2.ProgrammingError: syntax error at or near "'HOUSEID'"
LINE 1: ALTER TABLE HHV2PUB ADD COLUMN 'HOUSEID' text
My guess is that it has something to do with the single quotes ''
我的猜测是它与单引号有关
''
As of Psycopg 2.7 there is the safe sql
module : 从Psycopg 2.7开始,有安全的
sql
模块 :
from psycopg2 import sql
query = sql.SQL("alter table t add column {} text")
row1 = ('col1', 'col2')
for c in row1:
cursor.execute(query.format(sql.Identifier(c)))
With 2.6 and earlier: 使用2.6及更早版本:
Use psycopg2.extensions.AsIs
使用
psycopg2.extensions.AsIs
Adapter conform to the ISQLQuote protocol useful for objects whose string representation is already valid as SQL representation.
适配器符合ISQLQuote协议,该协议对字符串表示形式已作为SQL表示形式有效的对象很有用。
import psycopg2
from psycopg2.extensions import AsIs
conn = psycopg2.connect("host=localhost4 port=5432 dbname=cpn")
cursor = conn.cursor()
query = "alter table t add column %s text"
row1 = ('col1', 'col2')
for c in row1:
cursor.execute(query, (AsIs(c),))
conn.commit()
You cannot use SQL parameters for SQL object names . 您不能将SQL参数用于SQL对象名称 。 SQL parameters quote values explicitly so that they cannot be interpreted as such;
SQL参数显式引用值,以使它们不能被这样解释; that is one of the major reasons to use SQL parameters otherwise .
这是否则使用SQL参数的主要原因之一。
You'll have to use string interpolation here. 您必须在这里使用字符串插值。 Be extremely careful that you are not using user input to produce
c
here: 要特别小心 ,不要在此处使用用户输入生成
c
:
for c in row1:
cur.execute("ALTER TABLE HHV2PUB ADD COLUMN %s text" % c)
Psycopg2 does give you a method to mark parameters as 'already escaped' with psycopg2.extensions.AsIs()
, but the intention is for this to be used on already escaped data instead. Psycopg2确实为您提供了一种使用
psycopg2.extensions.AsIs()
将参数标记为“已经转义”的方法,但其目的是将其用于已转义的数据 。
A much better idea is to use the psycopg2.sql
extension to manage correct identifier escaping: 一个更好的主意是使用
psycopg2.sql
扩展名来管理正确的标识符转义:
from psycopg2 import sql
for c in row1:
cur.execute(
sql.SQL("ALTER TABLE HHV2PUB ADD COLUMN {} text").format(
sql.Identifier(c)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.