【问题标题】:How to insert json data into postgres database table如何将json数据插入postgres数据库表
【发布时间】:2021-07-16 07:42:23
【问题描述】:

我是初学者,正在尝试使用教程将 JSON 值插入数据库

我已经使用以下命令创建了表

CREATE TABLE table_name( id character varying(50),
                         data json NOT NULL,
                         active boolean NOT NULL,
                         created_at timestamp with time zone NOT NULL,
                         updated_at timestamp with time zone NOT NULL,
                         CONSTRAINT table_name_pkey PRIMARY KEY (id)
                       );

该表是使用 table_name 创建的。

现在我正在尝试将值插入数据库:

INSERT INTO table_name
SELECT id,data,active,created_at,updated_at
FROM json_populate_record (NULL::table_name,
     '{
        "id": "1",
        "data":{
                "key":"value"
                },
         "active":true,
         "created_at": SELECT NOW(),
         "updated_at": SELECT NOW()
       }'
  );

它会抛出以下错误

错误:JSON '{

类型的输入语法无效

谁能帮我解决 JSON 值并将其插入数据库?

【问题讨论】:

  • id 显然是使用整数值,为什么它是一个 varchar?

标签: json postgresql sql-insert


【解决方案1】:

您不能在 JSON 字符串中包含任意 SQL 命令。从 JSON “角度”来看,SELECT NOW() 是一个无效值,因为它缺少双引号。但即使您使用了"select now()",它也会作为 SQL 查询执行并替换为当前时间戳)。

但我不明白你为什么要把它包装成jsonb_populate_record。更好的解决方案(至少在我看来)是:

INSERT INTO table_name (id, data, active, created_at, updated_dat)
VALUES ('1', '{"key": "value"}', true, now(), now();

如果你真的想把事情复杂化,你需要使用字符串连接:

SELECT id,data,active,created_at,updated_at
FROM json_populate_record (NULL::table_name,
     format('{
        "id": "1",
        "data":{
                "key":"value"
                },
         "active":true,
         "created_at": "%s", 
         "updated_at": "%s"
       }', now(), now())::json
  );

【讨论】:

  • 第一个代码对我有用,但请将 id 值编辑为 1 而不是 "1" @a_horse_with_no_name
  • 您的 id 列定义为varchar,因此您需要将其作为字符串传递。在 JSON 值中,字符串写为 "1",而在 SQL 中,字符串写为 '1'
猜你喜欢
  • 2015-05-22
  • 2019-10-25
  • 2021-10-31
  • 2020-09-03
  • 2021-07-19
  • 1970-01-01
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多