PostgreSQL export result as CSV from remote server

半世苍凉 提交于 2019-12-07 16:11:32

Have you tried this? I do not have psql right now to test it.

echo “COPY (SELECT * from schema.products) TO STDOUT with CSV HEADER” | psql -o '/home/localfolder/products.csv'

Details:

-o filename   Put  all  output into file filename.  The path must be writable by the client.
echo builtin + piping (|) pass command to psql

From http://www.postgresql.org/docs/current/static/sql-copy.html:

Files named in a COPY command are read or written directly by the server, not by the client application.

So, you'll always want to use psql's \copy meta command.

The following should do the trick:

\copy (SELECT * FROM schema.products) to 'products.csv' with csv

If the above doesn't work, we'll need an error/warning message to work with.

You mentioned that the server is remote, however you are connecting to a localhost. Add the -h [server here] or set the ENV variable

export PGHOST='[server here]' 

The database name should be the last argument, and not with -d. And finally that command should have not failed, my guess is that that directory does not exist. Either create it or try writing to tmp.

I would ask you to try the following command:

psql -h [server here] -c "copy (select * from schema.products) to STDOUT csv header" DB > /tmp/products.csv

Aftr a while a good colleague deviced this solution which worked perfectly for my needs, hope this can help someone.

'ssh -l user [remote host] -p [port] \'psql -c "copy (select * from schema.table_name') to STDOUT csv header" -d DB\' > /home/localfolder/products.csv'

Very similar to idobr's answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!