0

I have below code to export a table data to a csv file:


                Connection con = new DBConnection().dbConnection();
                String query = "\\copy ( select * from user_login) to '/tmp/user_login.csv' delimiter ',' csv header;";

                System.out.println("QUERY: "+query );
                java.sql.Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
                stmt.executeQuery(query);

This throws below error:

QUERY: \copy ( select * from user_login) to '/tmp/user_login.csv' delimiter ',' csv header;
Exception in thread "main" org.postgresql.util.PSQLException: ERROR: syntax error at or near "\"
  Position: 1
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)
        at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)

When I execute the same query on postgres terminal, it works absolutely fine.

db_737=> \copy ( select * from user_login) to '/tmp/user_login.csv' delimiter ',' csv header; COPY 2746

Pls suggest is there any way to resolve this.

DB ss working fine

  • Postgres terminal client is not the same as JDBC. It understands commands that the JDBC driver does not. JDBC accepts only well-formed SQL, and the `\copy` command is specific to the postgres command-line client. It is not SQL. – Jim Garrison Nov 04 '22 at 00:44

0 Answers0