Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

linux - PostgreSQL CSV import from command line

I've been using the psql Postgres terminal to import CSV files into tables using the following

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

which works fine except that I have to be logged into the psql terminal to run it.

I would like to know if anyone knows of a way to do a command similar to this from the Linux shell command line similar to how Postgres allows a shell command like bellow

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

This allows the dumping of a database from the Linux shell without being logged into psql terminal.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The solution in the accepted answer will only work on the server and when the user executing the query will have permissions to read the file as explained in this SO answer.

Otherwise, a more flexible approach is to replace the SQL's COPY command with the psql's "meta-command" called copy which which takes all the same options as the "real" COPY, but is run inside the client (with no need for ; at the end):

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

As per docs, the copy command:

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.


In addition, if the the_file.csv contains the header in the first line, it can be recognized by adding header at the end of the above command:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...