我正在尝试使用 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/