package biblioteki;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

public class EksportCSV {

	public static void main(String[] args) {
		System.out.println("Zadaję zapytanie");

		try(Connection c = DriverManager.getConnection("jdbc:postgresql://localhost/hr", "kurs", "abc123");
				PreparedStatement stmt = c.prepareStatement("SELECT * FROM employees");
				ResultSet rs = stmt.executeQuery()) {
			
			System.out.println("Zapisuję do pliku");
			eksportujDoCSV(rs, "eksport.csv");
			System.out.println("Gotowe");
		} catch (SQLException | IOException e) {
			e.printStackTrace();
		}
	}

	static void eksportujDoCSV(ResultSet rs, String sciezka) throws SQLException, IOException {
		CSVFormat format = CSVFormat.Builder.create()
				.setDelimiter(';')
				.setHeader(rs)
				.build();
		
		try(PrintWriter out = new PrintWriter(sciezka);
			CSVPrinter printer = new CSVPrinter(out, format)) {
			printer.printRecords(rs);
		}
	}

}
