防止 python 转义 sql 查询中的引号

prevent python from escaping quotes in sql queries

我正在使用带有 postgis 扩展的 postgres 数据库。我必须使用 python 作为后端将数据插入到 postgres 中。我正在使用 psycopg2 进行连接,我的 python 版本是 3.7 。我无法推送我的数据,因为 python 一直在转义字符串文字。以下是我的代码。

def insert(lvalues):
    lvalues = [str(i) for i in lvalues]
    values = ', '.join(lvalues)
    return values


if __name__ == '__main__':
    cursor, conn = connect()
    cord = [
        [
            [
                67.774658203125,
                25.69103802005013
            ],
            [
                68.90625,
                24.367113562651262
            ],
            [
                73.970947265625,
                25.958044673317843
            ],
            [
                74.87182617187499,
                28.565225490654658
            ],
            [
                70.33447265624999,
                28.815799886487298
            ],
            [
                67.774658203125,
                25.69103802005013
            ]
        ]
    ]
    js = insert(('GISid', 'srid', 'familyid', 'geom', 'nameofgeom'))
    jst = '''{  "type": "Polygon","coordinates": ''' + str(cord) + ''',
                      "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}
            }'''


    print(cursor.mogrify(
        "INSERT INTO public.spatial_data(gid, srid, familyid, geom, nameofgeom) VALUES (103,4326,2,ST_GeomFromGeoJSON(%s),'polygon') ",
        (jst,)))

我得到的结果如下:

b'INSERT INTO public.spatial_data(gid, srid, familyid, geom, nameofgeom) VALUES (103,4326,2,ST_GeomFromGeoJSON(\'{  "type": "Polygon","coordinates": [[[67.774658203125, 25.69103802005013], [68.90625, 24.367113562651262], [73.970947265625, 25.958044673317843], [74.87182617187499, 28.565225490654658], [70.33447265624999, 28.815799886487298], [67.774658203125, 25.69103802005013]]],\n        "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}\n            }\'),\'polygon\') '

有人可以建议一种删除出现在 mogrify 结果中的 \ 和 \n 的方法吗? cursor 是 psycopg2 连接游标对象。 提前谢谢你。

如果您使用 cursor.execute 而不是 .mogrify 会怎样?听起来它已经在做正确的事情了...

  • 任何情况下的反斜杠都来自 print 语句,不会被发送到数据库。

  • 如果确实需要去掉换行符,它们都来自jst变量;使用类似的东西:jst.replace('\n', ' ')

尽管 mogrify 给出的语句类似于使用 execute 命令执行的语句,但它为我们提供了一个 repr 版本。如果计划直接使用 mogrify 输出应该会有问题,但如果您使用单独的执行语句,它 可能 导致错误。(不一定)。字符串替换帮我解决了这个问题。

jst.replace('\n', ' ').replace("\'",' ')