Search code examples
postgresqlcronexport-to-csvpsql

Postgres/PSQL - exporting automatically a query to CSV using a batchfile


when I do manually followed commands that work like a charm

psql "postgresql://server:myport/base?user=me&password=password" 

\COPY (SELECT *  FROM MyTable WHERE dt_dern_modif > '2021-12-21') TO 'C:\Users\Me\notifs_dump_cron.csv' DELIMITER ';' CSV HEADER;

I try to create a batch to save daily the content of a table in postgres to a CSV file and send it later vat ftp on a server.

I'm using windows 10 and psql 11.13

How can I do this export ?

I try to do something like that for the moment but that don't match : file.bat

    psql "postgresql://server:myport/base?user=me&password=password" -c "\COPY (SELECT *  FROM MyTable ') TO 'C:\Users\Me\notifs_dump_cron.csv' DELIMITER ';' CSV HEADER;"

And when I launch it that make me following response :

psql "postgresql://server:myport/base?user=me&password=password" -c "\COPY (SELECT * FROM bng_safcom_cen.cofi;) TO 'C:\Users\SG41RPichet\Documents\notifs_dump_cron.csv' DELIMITER ';' CSV HEADER;"
psql : attention : option supplémentaire « \COPY (SELECT * FROM bng_safcom_cen.cofi;) TO 'C:\Users\SG41RPichet\Documents\notifs_dump_cron.csv' DELIMITER ';' CSV HEADER; » ignorée
psql (11.13, serveur 10.5 (Debian 10.5-1.pgdg80+1))
Attention : l'encodage console (850) diffère de l'encodage Windows (1252).
            Les caractères 8 bits peuvent ne pas fonctionner correctement.
            Voir la section « Notes aux utilisateurs de Windows » de la page
            référence de psql pour les détails.
Connexion SSL (protocole : TLSv1.2, chiffrement : ECDHE-RSA-AES256-GCM-SHA384, bits : 256, compression : désactivé)
Saisissez « help » pour l'aide.

table=>

Solution

  • OK, that seems it's impossible to do that with connecting string. You must use a pgpass.conf file and do a file.bat like :

    psql -d base -h host -U me -w -p 5420 -c "\COPY (SELECT * FROM table WHERE dt_dern_modif > '2021-12-21') TO 'dump_cron.csv' DELIMITER ';' CSV HEADER;"