postgresql 如何将表数据导出到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4791288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 22:47:55  来源:igfitidea点击:

How to export table data to file

postgresql

提问by kallem

I would like to export a single Postgres table's data into a .csv file. Can anyone give me an example of how to do that?

我想将单个 Postgres 表的数据导出到 .csv 文件中。谁能给我一个如何做到这一点的例子?

回答by Peter Eisentraut

In psql:

在 psql 中:

\copy tablename to 'filename' csv;

回答by Nick Woodhams

First, log into the PostgreSQL console via the command line with the psqlcommand.

首先,使用命令通过命令行登录到 PostgreSQL 控制台psql

To export:

导出:

\connect database_name;
\copy my_table to 'my_table.csv' csv;
\q

To import:

导入:

\connect database_name;
\copy my_table FROM 'my_table.csv' DELIMITER ',' CSV;
\q

Done!

完毕!



Or, from a shell script!

或者,来自 shell 脚本!

export PGPASSWORD=dbpass
psql --dbname=dbpass --username=dbuser --host=127.0.0.1 -c "COPY (SELECT * FROM widget) TO stdout DELIMITER ',' CSV HEADER" > export.csv

Bonus AdviceUse pgcli, it's way better than psql

额外建议使用pgcli,它比 psql 好得多

回答by Joel Rein

When logged into psql:

登录 psql 时:

COPY tablename TO 'filename';

For more details, see this: http://www.postgresql.org/docs/current/static/sql-copy.html

有关更多详细信息,请参阅:http: //www.postgresql.org/docs/current/static/sql-copy.html