Is it possible to query Postgresql in order to get correct CSV line? For instance select concat (a,',',b) from t but with correctly escaped commas and quotes.
-
1) What version of Postgres? 2) What client are you using?Adrian Klaver– Adrian Klaver2022-10-31 23:11:29 +00:00Commented Oct 31, 2022 at 23:11
-
Version is 14.1. Client is self-written java app via jdbc connection.Alex– Alex2022-11-01 07:14:33 +00:00Commented Nov 1, 2022 at 7:14
Add a comment
|
1 Answer
A couple of options.
Using psql
select * from some_table \g (format=csv) output.csv
This will create a CSV file named output.csv.
\copy cell_per to 'output.csv' WITH(format csv, header, delimiter '|');
The above allows you to use the options as explained here COPY to do things like change the delimiter, quoting, etc.
You can also use COPY directly as a query. Though in that case it is important to note that COPY runs as the server user and can only write files to directories the server user has permissions on. The work around is to make the output go to STDOUT and and capture it. For instance using the Python driver psycopg2 there are copy methods copy.
2 Comments
Alex
Sorry it was worth to note that psql wasn't an option. Client is self written. I need an sql statement probably with postgres specific function to get properly formed CSV.
Adrian Klaver
There is a Postgres specific statement to output CSV it is
COPY as mentioned in the answer. If you are using the Postgres community JDBC driver then maybe this JDBC Copy?