[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1758
  • Last Modified:

how to put my two psql lines together in a batch file in order to have them executed.?

hello experts,

i'd like to create a batch file on windows, that when i click on it, it connects to postgresql and export with COPY a selection into a csv file.

I have my connection line and my export line, but if i paste them in a .bat file and launch the batch, only the connection is processed. The output file is not written, i  have the psql prompt that shows that i'm connected to the db but i'ts not what i expect.
i'd like my first line to connect, my second does the exports.

what am i doing wrong ? how can i correct this. ?

inside my .bat file.
psql -h localhost -U User -d my_db
COPY public.rs_container_today FROM 'C:/folder/today_container_status.csv' WITH DELIMITER '
,' ;
  • 3
  • 2
1 Solution
To run a single SQL command, I think you want:
  psql -h localhost -U User -d my_db -c "COPY ..."
toshi_Author Commented:
hello tel2,

thank you for your answer,
this case i exposed has only one command.

Do you think this is possible for several commands ?
i'm going to give it a try,


Hi toshi_,

As I understand it, connecting in the way you did, will put you into psql interactive mode, and I doubt that the next command in the batch file will run there, as batch file commands are run on the DOS shell (or whatever it's called these days).

And if you ever want to run multiple SQL commands after connecting, have a look at the "psql automated shell examples" section near the bottom of this psql cheat sheet:
Especially the "Run an sql batch script against a database" part.
toshi_Author Commented:
thank you very much,
Thanks for the points, toshi_ (or can I just call you "_" for short?).

At a guess, this might also work:
    TYPE command_file.sql | psql -h localhost -U User -d my_db
where the command_file.sql contains your SQL commands.  I'm not in a position to test it.  But using the "-c" option is probably easier, and should definitely work.

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now