python - 由于插入命令中的单引号而导致 psycopg2 语法错误

标签 python psycopg2

我正在尝试使用 psycopg2 执行“插入表”命令。我在一个函数中创建命令字符串,该函数返回以下形式的字符串:

create table %s (  %s %s , %s %s , %s %s , %s %s , %s %s , %s %s , %s %s , %s %s , %s %s , %s %s , %s %s , primary key %s );

该函数还返回一个字符串变量元组,我想用它来填充格式字符串:

('games', 'score_loser', 'integer', 'playoffs', 'boolean', 'record_loser', 'integer[]', 'broadcast', 'varchar(20)', 'date', 'date', 'id', 'varchar (30)', 'home_team', 'varchar (50)', 'record_winner', 'integer[]', 'winner', 'varchar (50)', 'loser', 'varchar (50)', 'score_winner', 'integer', 'id')

但是当我尝试执行该命令时,我遇到了一个问题,即元组中的变量被放入单引号中,这会导致 psycopg2 中出现语法错误:

psycopg2.ProgrammingError: syntax error at or near "'games'"

第 1 行:创建表 'games' ( 'score_loser' 'integer' , 'playoffs'...

有人可以告诉我应该做什么吗?

最佳答案

你不能这么做。来自 Psycopg documentation on query parameters :

Only query values should be bound via this method: it shouldn’t be used to merge table or field names to the query (Psycopg will try quoting the table name as a string value, generating invalid SQL). If you need to generate dynamically SQL queries (for instance choosing dynamically a table name) you can use the facilities provided by the psycopg2.sql module:

>>> cur.execute("INSERT INTO %s VALUES (%s)", ('numbers', 10))  # WRONG
>>> cur.execute(                                                # correct
...     SQL("INSERT INTO {} VALUES (%s)").format(Identifier('numbers')),
...     (10,))

关于python - 由于插入命令中的单引号而导致 psycopg2 语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55550458/

相关文章:

javascript - 使用 Python 在 Selenium 中运行 javascript

python - psycopg2 安装错误 - 库未加载 : libssl. dylib

python - 当我迭代游标时 psycopg2 在做什么?

python - 使用 Psycopg2 和 unnest 时的 "Unknown"数据类型

python - 使用 PIL 和 OpenCV 2 在 Python 中轴越界错误

python - 按列就地排序在切片上失败

python-3.x - 如何使用 psycopg2.extras.execute_values 更新 ON CONFLICT

PostgreSQL 字段中的 Django ProgrammingError

python - 如何从 Jinja 模板调用方法?

python - 狮身人面像 :ivar tag goes looking for cross-references