【问题标题】:Inputting string into PostgreSQL results in syntax error at single quote将字符串输入 PostgreSQL 导致单引号出现语法错误
【发布时间】:2017-06-16 16:39:04
【问题描述】:

我正在运行一个非常大的数据集,其中每一行都有一个 json 对象。在经过近 10 亿行之后,我的交易突然出现错误。

我正在使用 Python 3.x 和 psycopg2 来执行我的事务。

我要写的json对象如下:

{"message": "ConfigManager: Config if valid JSON but doesn't seem to have the correct schema. Adopting new config aborted."}

并且 psycopg2 报告以下内容:

syntax error at or near "t"
LINE 3: ...": "ConfigManager: Config if valid JSON but doesn't seem to ...

我知道问题是单引号,但是我不知道如何逃避这个问题,以便可以将 json 对象传递到我的数据库。

我的 json 列的类型为 jsonb,名为 first_row

所以如果我尝试:

INSERT INTO "356002062376054" (first_row) VALUES {"message": "ConfigManager: Config if valid JSON but doesn't seem to have the correct schema. Adopting new config aborted."}

我仍然收到错误消息。我似乎没有做任何事情来解决这个问题。我尝试用\ 转义t 并将双引号更改为单引号,并删除大括号。没有任何效果。

我相信我记得做这件事很重要

`json.dumps({"message": "ConfigManager: Config if valid JSON but doesn't seem to have the correct schema. Adopting new config aborted."})` in my python code and yet I am getting this problem.

【问题讨论】:

  • 您必须转义 ' 并将值加上引号。或使用不同的引号,如$not_sgl_quote$ 或更好的准备语句,然后传递值
  • 使用$ 似乎不起作用
  • 例如:INSERT INTO "356002062376054" (first_row) VALUES e'{"message": "ConfigManager: Config if valid JSON but doesn\'t seem to have the correct schema. Adopting new config aborted."}'
  • 我的错:INSERT INTO "356002062376054" (first_row) SELECT e'{"message": "ConfigManager: Config if valid JSON but doesn\'t seem to have the correct schema. Adopting new config aborted."}'
  • 或:INSERT INTO "356002062376054" (first_row) values (E'{"message": "ConfigManager: Config if valid JSON but doesn\'t seem to have the correct schema. Adopting new config aborted."}');

标签: python json postgresql syntax-error psycopg2


【解决方案1】:

您可以为此使用美元符号约束或 C 样式转义。例如docs:

转义字符串常量通过写字母 E(大写 或小写)就在开始单引号之前,例如,E'foo'

那么:

INSERT INTO "356002062376054" (first_row) SELECT e'{"message": "ConfigManager: Config if valid JSON but doesn\'t seem to have the correct schema. Adopting new config aborted."}'

INSERT INTO "356002062376054" (first_row) values (E'{"message": "ConfigManager: Config if valid JSON but doesn\'t seem to have the correct schema. Adopting new config aborted."}');

应该适合你

【讨论】:

    【解决方案2】:

    您必须在 SQL 中将单引号加倍才能对其进行转义。

    但是你有这个问题意味着你的代码容易受到SQL injection的攻击。您应该在执行语句时使用parameterized statements 并将字符串作为参数提供。如果你这样做,问题就会消失。

    psycopg2 文档有这个可怕但有充分理由的警告:

    警告:从不、从不、从不使用 Python 字符串连接 (+) 或字符串参数插值 (%) 将变量传递给 SQL 查询字符串.甚至在枪口下也没有。

    【讨论】:

    • 什么是准备好的语句,我应该如何用双单引号将其转义。一些示例将是首选:P
    • 我添加了指向 psycopg2 文档的链接。这应该说清楚。
    • 谢谢。我正在使用"{}".format(some_str) 来做这件事。
    • 如果遇到单引号问题,则解决方案不好。如果您真的不想使用最佳解决方案,您将不得不自己将所有' 转为'' 并祈祷您不要忘记任何一个。
    猜你喜欢
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多