【问题标题】:How to read table data row by row of postgres db using shell script如何使用shell脚本逐行读取postgres db的表数据
【发布时间】:2020-07-22 02:59:26
【问题描述】:

如何使用shell脚本逐行读取postgres db的表数据。

我试过了:

psql -d db_name -t -c "SELECT * FROM table_name" | while read -a Record ; do
echo $Record[0]
echo $Record[1]
done

但是这个方法给我的数据如下:

Apple
|

为什么当我只获取行数据时会出现这个|

实际上我想从一个 db 表数据中创建 json 对象。 格式:

column-name : value,
column-name : value
..... ; 

类似的东西

Table name -> student

Fields :
id : string
name : string
age : int
inSchool : boolean

Table data : 

ID   Name   Age  inSchool
1    Amit   18    Yes
2    Sunil  21    No
3    Anil   17    Yes

我想要的输出:

[
{
   id : 1,
   name : Amit,
   age : 18,
   inSchool : 1;
}, 
{
   id : 2,
   name : Sunil,
   age : 21,
   inSchool : 0;
}, 
{
   id : 3,
   name : Anil,
   age : 17,
   inSchool : 1;
}
]

如果有什么好的方法,请帮帮我。

【问题讨论】:

  • 如果你想要json,那为什么不直接使用jsonb_agg(to_jsonb(table_name))呢?
  • @a_horse_with_no_name 你能给我举个例子吗?
  • -t 关闭列名。它不会关闭字段分隔符。
  • 请提供表格描述 (DDL) 和示例数据,以文本形式无图片
  • @Belayer 我已经编辑了我的问题并包含了示例数据。请看一下

标签: postgresql shell psql


【解决方案1】:

让 Postgres 在关闭标题格式后进行聚合并将输出假脱机到文件中:

postgres=> \t
Tuples only is on.
postgres=> \o data.json
postgres=> select jsonb_agg(to_jsonb(s)) from student s;

或者在一行中:

psql -d db_name -t -c "select jsonb_agg(to_jsonb(s)) from student s" -o data.json

之后,文件 data.json 将包含整个表作为一个巨大的 JSON 数组。

【讨论】:

  • 这里的 s 和 t 是什么 select jsonb_agg(to_jsonb(s)) from student t ?
  • @NitinSinghal:抱歉,应该只有s - 这是table alias
猜你喜欢
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 2011-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多