使用psycopg2将列名作为参数传递给PostgreSQL

使用psycopg2将列名作为参数传递给PostgreSQL,第1张

使用psycopg2将列名作为参数传递给PostgreSQL

从Psycopg 2.7开始,有安全

sql
模块:

from psycopg2 import sqlquery = sql.SQL("alter table t add column {} text")row1 = ('col1', 'col2')for c in row1:    cursor.execute(query.format(sql.Identifier(c)))

使用2.6及更早版本:

采用

psycopg2.extensions.AsIs

适配器符合ISQLQuote协议,该协议对字符串表示形式已作为SQL表示形式有效的对象很有用。

import psycopg2from psycopg2.extensions import AsIsconn = 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()


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5617247.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存