您可以將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查詢。我會研究:) –