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

Asked

Viewed 528 times

1

This is my code, which unfortunately does not export 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 tried everything but I could not export with the table column names! What should I do?

SQL code (to be executed directly in DBMS):

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

Sql commands when executed directly in the database work perfectly, but when I try to turn into jdbc encounter obstacles.

  • 1

    https://docs.oracle.com/javase/8/docs/api/java/sql/ResultSetMetaData.html

  • @Victorstafusa Thanks for the tip, but how could I mount the query?

  • 1

    I don’t know yet, but I’m thinking about it.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.