【问题标题】:Escape single quote in the input parameter in a Function in postgresql在 postgresql 的函数中的输入参数中转义单引号
【发布时间】:2019-07-26 12:12:48
【问题描述】:

我有一个带有单引号的 JSON,其中一个字段如下所示。创建一个以 JSON 作为输入参数的函数,并直接从应用程序调用。 如果将其读入函数,我至少会使用 regexp_replace。

例如:

select '{
  "phrase": "foo",
  "phrase_1": "'bar'"
  }' :: json 

syntax error at or near "'"

  }'"
LINE 3:   "phrase_1": "'bar'"

这是一个错误的输出。所以我的实际问题是这个 json 被直接读入我的函数中。

create or replace function f_n(in json) -- it is failing to read here
returns text
---
---
end;
$$

那么我可以在这里做些什么来避免 postgresql 中的此类问题?

【问题讨论】:

    标签: postgresql postgresql-10 postgresql-11


    【解决方案1】:

    SQL中单引号需要重复to escape them:

    select '{
      "phrase": "foo",
      "phrase_1": "''bar''"
      }'::json;
    

    或者使用 Postgres 的dollar quoting 来避免这种情况:

    select $j${
      "phrase": "foo",
      "phrase_1": "'bar'"
      }$j$::json;
    

    将其作为参数传递给函数时,效果相同:

    select f_n('{
      "phrase": "foo",
      "phrase_1": "''bar''"
      }'::json);
    

    select f_n($j${
          "phrase": "foo",
          "phrase_1": "'bar'"
          }$j$::json);
    

    【讨论】:

      猜你喜欢
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      • 2014-07-28
      • 2015-05-27
      • 2013-03-30
      相关资源
      最近更新 更多