如何以 CSV 格式从 postgres 数据库下载所有表

How to download all tables from a postgres database as CSV format

我想以 CSV 格式从 Postgres 数据库下载所有表格。下面是我用来从特定数据库下载所有表的示例 shell 脚本。

但脚本不是 运行 在 echo "No User/Role name provided set default User?Role postgres." User=postgres fi 命令之后。

或者任何人请向我建议任何脚本或 SQL 查询以将所有表格下载为 CSV 格式。提前致谢。

#set -x
read -p "Please provide Schema name   " Schema
if [ -z $Schema ]
then
    echo "No Schema name provided set default schema public."
Schema=public
fi
read -p "Please provide Database name  " Db
if [ -z $Db ]
then
    echo "No Database name provided set default database postgres."
Db=postgres
fi
read -p "Please provide Postgres Role/User name  " User
if [ -z $User ]
then
    echo "No User/Role name provided set default User?Role postgres."
User=postgres
fi

echo " Schema Name is-->$Schema   Database Name--> $Db   User Name-->$User "

psql -U $User -h localhost -Atc "select tablename from pg_tables where schemaname='$Schema'" $Db |\
  while read TABLENAME; do
        echo "$TABLENAME"
    psql -U $User -h localhost -c "COPY $Schema.$TABLENAME TO STDOUT WITH CSV HEADER" $Db  > $TABLENAME.csv
  done

您似乎进行了重定向,导致脚本停止。更改行:

echo " Schema Name is-->$Schema   Database Name--> $Db   User Name-->$User "

成为:

echo " Schema Name is--"'>'"$Schema   Database Name--"'>'" $Db   User Name-->$User "

符号>在shell中有特殊含义,必须转义