rob*_*ill 16 postgresql backup csv
我有一个包含很多模式的数据库,我想将每个表内容转储到 CSV。我知道 COPY 命令,但我不确定如何编写一些脚本来读取模式中的所有表并针对它们执行 COPY。
Eze*_*nay 27
这是一个可以执行您想要的操作的 shell 脚本:
SCHEMA="myschema"
DB="mydb"
psql -Atc "select tablename from pg_tables where schemaname='$SCHEMA'" $DB |\
while read TBL; do
psql -c "COPY $SCHEMA.$TBL TO STDOUT WITH CSV" $DB > $TBL.csv
done
Run Code Online (Sandbox Code Playgroud)
确保将 DB 和 SCHEMA 变量设置为您的特定数据库和架构。
包装 psql 命令使用 A 和 t 标志根据传递给 c 命令的字符串生成表列表。
小智 7
如果您需要导出所有模式,这里是脚本
PGDATABASE="db"
PGUSER="user"
psql -Atc "select schema_name from information_schema.schemata" |\
while read SCHEMA; do
if [[ "$SCHEMA" != "pg_catalog" && "$SCHEMA" != "information_schema" ]]; then
psql -Atc "select tablename from pg_tables where schemaname='$SCHEMA'" |\
while read TBL; do
psql -c "COPY $SCHEMA.$TBL TO STDOUT WITH CSV DELIMITER ';' HEADER ENCODING 'UTF-8'" > $SCHEMA.$TBL.csv
done
fi
done
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20743 次 |
最近记录: |