Psycopg循环生成SQL插入语句时表名引发语法错误求解
问题:Psycopg插入PostgreSQL时表名字段语法错误
问题场景
使用Psycopg向PostgreSQL批量插入数据,插入语句在for循环中,每次迭代的表名(region变量)不同。当前代码如下:
insert_string = sql.SQL( "INSERT INTO {region}(id, price, house_type) VALUES ({id}, {price}, {house_type})").format( region=sql.Literal(region), id=sql.Literal(str(id)), price=sql.Literal(price), house_type=sql.Literal(house_type)) cur.execute(insert_string)
变量region、id、price、house_type均在循环内定义。运行时触发语法错误:
psycopg2.errors.SyntaxError: syntax error at or near "'Gorton'"
LINE 1: INSERT INTO 'Gorton'(id, price, house_typ...
^
其中'Gorton'是该次迭代中region变量的值,疑惑点是表名字段该用sql.Literal还是sql.Identifier。
问题原因
PostgreSQL中,表名属于标识符(Identifier),不是字面量(Literal)。用sql.Literal()会给表名加上单引号,而SQL语法里标识符不需要单引号(特殊场景需用双引号),因此导致语法错误。
修正方案
表名字段改用sql.Identifier()处理,字段值保持sql.Literal()不变:
insert_string = sql.SQL( "INSERT INTO {region}(id, price, house_type) VALUES ({id}, {price}, {house_type})").format( region=sql.Identifier(region), # 替换为sql.Identifier id=sql.Literal(str(id)), price=sql.Literal(price), house_type=sql.Literal(house_type)) cur.execute(insert_string)
补充说明
sql.Identifier()用于处理SQL中的标识符(表名、列名等),会自动处理特殊字符(比如表名含空格或关键字时,自动添加双引号)。sql.Literal()用于处理值类型参数(字符串、数字等),会自动添加单引号并转义特殊字符,避免SQL注入风险。
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

