您可以将JSON提供给提取信息并将其插入表中的SQL语句。如果JSON恰好有名称为表列,你可以做这样的事情:
with customer_json (doc) as (
values
('[
{
"id": 23635,
"name": "Jerry Green",
"comment": "Imported from facebook."
},
{
"id": 23636,
"name": "John Wayne",
"comment": "Imported from facebook."
}
]'::json)
)
insert into customer (id, name, comment)
select p.*
from customer_json l
cross join lateral json_populate_recordset(null::customer, doc) as p
on conflict (id) do update
set name = excluded.name,
comment = excluded.comment;
的新客户将被插入,现有的将被更新。 “魔术”部分是生成JSON对象的关系表示的json_populate_recordset(null::customer, doc)
。
以上假设表定义是这样的:
create table customer
(
id integer primary key,
name text not null,
comment text
);
如果数据为文件提供的,你需要首先把该文件到一些数据库中的表。例如:
create unlogged table customer_import (doc json);
然后将文件上传到该表的单个行中,例如,在psql
使用\copy
命令(或任何你的SQL客户端提供):
\copy customer_import from 'customers.json' ....
然后你可以使用上面的语句,只是删除CTE和使用临时表:
insert into customer (id, name, comment)
select p.*
from customer_import l
cross join lateral json_populate_recordset(null::customer, doc) as p
on conflict (id) do update
set name = excluded.name,
comment = excluded.comment;
”*没有触及sql *“否。与说SQL的关系数据库进行交互的唯一方式就是SQL。 –
@a_horse_with_no_name哦...我很确定,然后我可以简单地将我的JSON转换为SQL查询。我会研究:) –