使用Postgres在Python中用单引号形成insert语句

2024-04-26 23:11:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为comments的字段。 我正在有效地尝试将值从一个大表读入多个表。 因此,我的select查询为我获取注释字段。在

我正在构建一个Python脚本来执行从表到表的复制。 当我的插入查询遇到一个注释字段时,它将失败,比如“对不起!我们无法处理您的订单”,因为只有一个报价。在

我试过用$报价,但没用

这就是我要做的

#!/usr/bin/python

import psycopg2

conn = psycopg2.connect("dbname='postgres' user='postgres' host='localhost' )
mark=conn.cursor()
/* fectching the rows and doing other stuff */

addthis="insert into my_table(something) values("$$"+str(row[8])+"$$")
mark.execute(addthis)
conn.commit()

感谢你的帮助!在


Tags: 订单import脚本binusrpostgresconnselect
2条回答
  1. insert语句应使用占位符。对于psycopg2,它是%s。在
  2. 您应该将参数作为第二个参数传递给execute()。这样,您就不会引用问题,并且可以防止SQL注入攻击。在

例如:

addthis = "INSERT INTO my_table (something) VALUES (%s);"
mark.execute(addthis, ('a string you wish to insert',))

您可以使用占位符,正如bernie建议的那样。这是首选方法。
但是,在某些情况下不可能使用占位符。然后你必须手动逃离库特斯。这是通过反斜杠来完成的:

addthis="insert into my_table(something) values(%s)" % str(row[8]).replace('"', r'\"').replace("'", r"\'")
mark.execute(addthis)

相关问题 更多 >