linux - 从命令行导入 PostgreSQL CSV

我一直在使用 psql Postgres 终端使用以下方法将 CSV 文件导入表中

COPY tbname FROM
'/tmp/the_file.csv'
delimiter '|' csv;

除了我必须登录到 psql 终端才能运行它之外,它工作正常。

我想知道是否有人知道从 Linux shell 命令行执行类似于此命令的方法,类似于 Postgres 如何允许像下面这样的 shell 命令

/opt/postgresql/bin/pg_dump dbname > /tmp/dbname.sql

这允许在不登录 psql 终端的情况下从 Linux shell 转储数据库。

最佳答案

已接受答案中的解决方案仅适用于服务器,并且当执行查询的用户将有权读取文件时,如 this SO answer 中所述.

否则,更灵活的方法是替换 SQL 的 COPY带有 psql 's "meta-command" called \copy 的命令其中which takes all the same options as the "real" COPY, but is run inside the client (最后不需要 ;):

psql -c "\copy tbname FROM '/tmp/the_file.csv' delimiter '|' csv"

As per docs , \copy命令:

Performs a frontend (client) copy. This is an operation that runs an SQL COPY command, but instead of the server reading or writing the specified file, psql reads or writes the file and routes the data between the server and the local file system. This means that file accessibility and privileges are those of the local user, not the server, and no SQL superuser privileges are required.


此外,如果 the_file.csv包含第一行的标题,可以通过添加header来识别在上述命令的最后:

psql -c "\copy tbname FROM '/tmp/the_file.csv' delimiter '|' csv header"

https://stackoverflow.com/questions/28602647/

相关文章:

c++ - pthread互斥体的开销?

linux - 用户脚本位置 linux (debian etch)

linux - 安装 gitLab 缺少现代化工具?

windows - 帮助我让我的 windows cmd.exe 控制台更像一个 Linux 终端

linux - 如何将文件从远程服务器复制到本地计算机?

linux - 为什么在 find 命令中使用 dirname 会为每个匹配项提供点?

linux - 使用包管理器时如何管理 Perl 模块?

linux - 禁用内存地址的随机化

linux - 如何将文件夹中的文件列表发送到Linux中的txt文件

ruby - Gemfile.lock 写入错误,权限?