我一直在使用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
这允许从Linux shell转储数据库而无需登录到psql终端 .
4 回答
如PostgreSQL文档(II. PostgreSQL Client Applications - psql)中所述,您可以使用开关
-c
将命令传递给psql
:接受的答案中的解决方案仅适用于服务器,并且当执行查询的用户有权读取文件时,如this SO answer中所述 .
否则,更灵活的方法是用psql's "meta-command" called \copy替换SQL的
COPY
命令which takes all the same options as the "real" COPY, but is run inside the client(最后不需要;
):As per docs,
\copy
命令:此外,如果
the_file.csv
包含第一行中的 Headers ,则可以通过在上述命令的末尾添加header
来识别它:最灵活的方法是使用shell
HERE document
,它允许您在查询中使用shell变量,甚至是内部(双引号或单引号)引号:要完成之前的answer,我建议: