How to export a table from postgres with column names to csv format with jdbc?

1

This is my code, which unfortunately does not export the column names:

package net.viralpatel.java;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.postgresql.copy.CopyManager;
import org.postgresql.core.BaseConnection;

public class BackUpBancoEmCSVSemCabecalho {

    private static String JDBC_CONNECTION_URL = "jdbc:postgresql://localhost:5432/NomeDoBanco";

    public static void main(String[] args) throws SQLException, FileNotFoundException, IOException {

        CopyManager copyManager = new CopyManager((BaseConnection) getCon());
        File file = new File("C:\temp\produtos.csv");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        String query = "Select * from Produto";

//and finally execute the COPY command to the file with this method:
        copyManager.copyOut("COPY (" + query + ") TO STDOUT WITH (FORMAT CSV)", fileOutputStream);
    }

    private static Connection getCon() {
        Connection connection = null;
        try {
            Class.forName("org.postgresql.Driver");
            connection = DriverManager.getConnection(JDBC_CONNECTION_URL, "postgres", "123");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.getNextException();

            e.getMessage();
        }
c
        return connection;
    }
}

I've tried everything but I could not export with the column names of the table! What should I do?

SQL code (to be executed directly in the DBMS):

copy produto  from 'c:/temp/produtos.csv' with csv header;
copy (select * from produto) to 'c:/temp/produtos.csv' with csv header;

The sql commands when executed directly in the database work perfectly, but when attempting to transform into jdbc encounter obstacles.

    
asked by anonymous 10.01.2017 / 19:47

0 answers