使用 psycopg2 将列名作为参数传递给 PostgreSQL [英] Pass column name as parameter to PostgreSQL using psycopg2

查看:32
本文介绍了使用 psycopg2 将列名作为参数传递给 PostgreSQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 psycopg2

row1 是要添加到表中的列名列表.我可以手动执行此操作,但是当我尝试以编程方式执行此操作时出现错误.

row1 below is a list of column names to be added to the table. 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,))

错误是:

    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

我的猜测是它与单引号''

推荐答案

从 Psycopg 2.7 开始,有安全的 sql 模块:

As of Psycopg 2.7 there is the safe sql module:

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)))

使用 2.6 及更早版本:

With 2.6 and earlier:

使用psycopg2.extensions.AsIs

适配器符合 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()

这篇关于使用 psycopg2 将列名作为参数传递给 PostgreSQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆