python - 尝试在 Python 上编写注入(inject)安全的 PostgreSQL 查询时出现 "Psycopg2.error column doesn' t exist"错误

标签 python postgresql psycopg2

我正在编写一个函数,使用 psycopg2 库为 PostgreSQL 数据库动态创建插入/更新/选择查询。

我一直在尝试根据 psycopg2 documentation 提供的建议编写注入(inject)安全的函数- 使用sql.Sql 方法正确组合查询。所有参数(表名、要插入的列、值)都动态传递给函数:

def insert(table, columns: list, values: list):

    query = sql.SQL('INSERT INTO {} ({}) VALUES ({});').format(
                    sql.Identifier(table),
                    sql.SQL(', ').join(map(sql.Identifier, columns)),
                    sql.SQL(', ').join(map(sql.Identifier, values))
                   )
    cursor = foo_connection.cursor()
    cursor.execute(query)

当我尝试测试功能时:

insert('test_table', ['col1', 'col2', 'col3'], ['1', '2', '3'])

我收到以下错误:

psycopg2.errors.UndefinedColumn: column "1" does not exist
LINE 1: ...e" ("col1", "col2", "col3") VALUES ("1", "2", ...

我没有理解这个错误,因为从技术上讲它甚至不是一列,它是一个要插入的值。

我认为查询的组成不正确,但 print(query.as_string(foo_connection)) 的结果表明它似乎是正确的:

INSERT INTO "test_table" ("col1", "col2", "col3") VALUES ("1", "2", "3");

官方文档没有涵盖这种情况。谷歌搜索也没有给我答案。

那么,问题是:

  1. 我做错了什么?
  2. 如何使这段代码起作用?

最佳答案

正如 Laurenz 所说,在 psycopg2 文档中,它是这样写的:

Identifiers usually represent names of database objects, such as tables or fields.

我还看到了 Literals 对象:

representing an SQL value to include in a query.

也许您可以在格式化查询时尝试用文字替换标识符:

query = sql.SQL('INSERT INTO {} ({}) VALUES ({});').format(
                sql.Identifier(table),
                sql.SQL(', ').join(map(sql.Identifier, columns)),
                sql.SQL(', ').join(map(sql.Literals, values))
               )

关于python - 尝试在 Python 上编写注入(inject)安全的 PostgreSQL 查询时出现 "Psycopg2.error column doesn' t exist"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57604339/

相关文章:

python - python 中的 Timeit 模块无法正常运行

python - 使用 pycountry 和 gettext 将翻译后的国家名称转换为 alpha2

python - 打印多行字符串,水平堆叠和对齐

Python:查找两列数据的周期

Postgresql ORDER BY 没有按预期工作

node.js - 无法安装 node-postgres

python - 如何使用 d3.js 从 postgresql 获取数据

postgresql - psycopg2 查询远程数据库

python - 使用哪些 gui 元素?

postgresql - Postgresql 连续归档对于维护完整的数据库历史记录是否实用?