복붙노트

[SQL] CSV 또는 Excel로 SQL 쿼리 결과 내보내기

SQL

CSV 또는 Excel로 SQL 쿼리 결과 내보내기

나는 CSV 또는 Excel 파일에 SQL 쿼리의 결과를 작성하고 특정 폴더에 저장합니다. 나는 다음과 같은 요청이 :

해결법

  1. ==============================

    1.openCSV의 API의 사용으로, 당신은 CSV 파일에 데이터를 내보낼 수 있습니다.

    openCSV의 API의 사용으로, 당신은 CSV 파일에 데이터를 내보낼 수 있습니다.

    CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), '\t');
    Boolean includeHeaders = true;
    
    java.sql.ResultSet myResultSet = .... //your resultset logic here
    
    writer.writeAll(myResultSet, includeHeaders);
    
    writer.close();
    
  2. ==============================

    2.그것은 어떤 도구에서 수출 결과 집합 데이터 어렵다.

    그것은 어떤 도구에서 수출 결과 집합 데이터 어렵다.

    예는 : .CSV 파일로 결과 집합 데이터를 내보내는 동안 데이터가 포함되어있는 경우는 ()가 제대로 내 보내지 않습니다

    자바 코드 아래를 참조하십시오 :

    완벽하게 어떤 어떤 쿼리 입력 및 결과 집합의 모든 데이터 유형을 작동

    package com.demo.export;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.WorkbookFactory;
    
    public class dataExportService {
        public void getDefendants(Connection con , String db) throws Exception  { 
            @SuppressWarnings("unused")
            Workbook readWorkbook = WorkbookFactory.create(new FileInputStream(".xls file path(C:\\Users\\CEPL\\Desktop\\test.xls)") );
            @SuppressWarnings("resource")
            Workbook writeWorkbook = new HSSFWorkbook();
            Sheet desSheet = writeWorkbook.createSheet("new sheet");
    
            Statement stmt = null;
            ResultSet rs = null;
            try{
                String query ="QUERY";
    
                stmt = con.createStatement();
                rs = stmt.executeQuery(query);
                ResultSetMetaData rsmd = rs.getMetaData();
                int columnsNumber = rsmd.getColumnCount();
    
                Row desRow1 = desSheet.createRow(0);
                for(int col=0 ;col < columnsNumber;col++) {
                    Cell newpath = desRow1.createCell(col);
                    newpath.setCellValue(rsmd.getColumnLabel(col+1));
                }
                while(rs.next()) {
                    System.out.println("Row number" + rs.getRow() );
                    Row desRow = desSheet.createRow(rs.getRow());
                    for(int col=0 ;col < columnsNumber;col++) {
                        Cell newpath = desRow.createCell(col);
                        newpath.setCellValue(rs.getString(col+1));  
                    }
                    FileOutputStream fileOut = new FileOutputStream(".xls file path(C:\\Users\\CEPL\\Desktop\\test.xls)");
                    writeWorkbook.write(fileOut);
                    fileOut.close();
                }
            }
            catch (SQLException e) {
                System.out.println("Failed to get data from database");
            }
        }
    
    }
    
  3. ==============================

    3.가장 간단한 솔루션입니다.

    가장 간단한 솔루션입니다.

    홈페이지 방법

     private List<String> resultSetArray=new ArrayList<>();
     private String username ="";     // Enter DB Username
     private String password = "";    // Enter DB password
     private String url = "";         // Enter DB URL
    
     Connection connection=DriverManager.getConnection(url,user,pwd);   
    
     public static void main(String args[]) throws Exception{
    
            fetchDataFromDatabase("SQL queries", connection);
            printToCsv(resultArray);                
    
     }
    

    데이터베이스에서 데이터를 가져 오기

    아래의 코드 테이블의 열들의 수를 카운트하고, 그 결과 어레이에 저장한다.

    private void fetchDataFromDatabase(String selectQuery,Connection connection) throws  Exception{
                try {
    
    
                    Statement stmt = connection.createStatement();
                    ResultSet rs = stmt.executeQuery(selectQuery);
                    int numCols = rs.getMetaData().getColumnCount();
    
                    while(rs.next()) {
                        StringBuilder sb = new StringBuilder();
    
                        for (int i = 1; i <= numCols; i++) {
                            sb.append(String.format(String.valueOf(rs.getString(i))) + " ");
    
                        }
                        resultSetArray.add(sb.toString());
    
                    }
    
                } catch (SQLException e) {
                    LOGGER.error("Sql exception " + e.getMessage());
                }
    
            }
    

    printToCsv

     public static void printToCsv(List<String> resultArray) throws Exception{
    
            File csvOutputFile = new File(file_name);
            FileWriter fileWriter = new FileWriter(csvOutputFile, false);
    
    
            for(String mapping : resultArray) {
                fileWriter.write(mapping + "\n");
             }
    
            fileWriter.close();
    
        }
    
  4. ==============================

    4.다음은 그 예이다 :

    다음은 그 예이다 :

    import java.io.*;
    import java.sql.*;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    
    public class ExcelFile {
            public static void main(String[] args) {
                    try {
                            Class.forName("com.mysql.jdbc.Driver").newInstance();
                            Connection connection = DriverManager.getConnection(
                                            "jdbc:mysql://localhost:3306/test", "root", "root");
                            PreparedStatement psmnt = null;
                            Statement st = connection.createStatement();
                            ResultSet rs = st.executeQuery("Select * from student");
    
                            HSSFWorkbook wb = new HSSFWorkbook();
                            HSSFSheet sheet = wb.createSheet("Excel Sheet");
                            HSSFRow rowhead = sheet.createRow((short) 0);
                            rowhead.createCell((short) 0).setCellValue("Roll No");
                            rowhead.createCell((short) 1).setCellValue("Name");
                            rowhead.createCell((short) 2).setCellValue("Class");
                            rowhead.createCell((short) 3).setCellValue("Marks");
                            rowhead.createCell((short) 4).setCellValue("Grade");
    
                            int index = 1;
                            while (rs.next()) {
    
                                    HSSFRow row = sheet.createRow((short) index);
                                    row.createCell((short) 0).setCellValue(rs.getInt(1));
                                    row.createCell((short) 1).setCellValue(rs.getString(2));
                                    row.createCell((short) 2).setCellValue(rs.getString(3));
                                    row.createCell((short) 3).setCellValue(rs.getInt(4));
                                    row.createCell((short) 4).setCellValue(rs.getString(5));
                                    index++;
                            }
                            FileOutputStream fileOut = new FileOutputStream("c:\\excelFile.xls");
                            wb.write(fileOut);
                            fileOut.close();
                            System.out.println("Data is saved in excel file.");
                            rs.close();
                            connection.close();
                    } catch (Exception e) {
                    }
            }
    }
    

    참고

  5. ==============================

    5.이것은 내 솔루션입니다. 코드는 메인 클래스에 삽입 :

    이것은 내 솔루션입니다. 코드는 메인 클래스에 삽입 :

    import java.io.*;
    import java.sql.*;
    import com.company.*;
    /**
     * Created by MAXNIGELNEGRO
    */
      String[] filePath =       new String[] {"C:\\Users\\Documents\\MyFile.csv"};
      String[] driverDB =       new String[] {"oracle.jdbc.driver.OracleDriver"};
      String[] stringConnDB =   new String[] {"jdbc:oracle:thin:@//127.0.0.1:1881/mydb"};
      String[] userDB =         new String[] {"pippo"};
      String[] passDB =         new String[] {"pluto"};
      String[] charSep =        new String[] {";"};
      Boolean colomn=   new Boolean (true);
      String[] queryDB =        new String[] {"select * FROM MYQUERY"};
    
    
    try{
        System.out.println("---------------File exist?------------" + filePath[0]);
        File fileTemp = new File(filePath[0].toString());
        if (fileTemp.exists()){ 
            fileTemp.delete();
            System.out.println("---------------DELETE FILE------------" + filePath[0] );
                    } 
       System.out.println("QUERY: ---->"+ queryDB[0].toString());
       exportQueryToCsv exp = new exportQueryToCsv();
       exp.exportQueryToCsv(filePath,driverDB,stringConnDB,userDB,passDB,queryDB, colomn,charSep);
       if (fileTemp.exists()){ 
         System.out.println("---File created---" + filePath[0]);
      }
    
    }
    catch(Exception e){
             e.printStackTrace();
          }
    

    핵심 클래스 :

    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    /**
     * Created by MAXNIGELNEGRO
     */
    public class exportQueryToCsv {
        public exportQueryToCsv(){}
        public static void  exportQueryToCsv (String[] filename, String[] driverDB, String[] connDB
                                                , String[] userDB, String[] passDB, String[] queryDB, Boolean intestaFile
                                                , String[] charSep) throws SQLException, IOException {
            Statement stmt=null;
            ResultSet rset=null;
            Connection conn=null;
            try { DBConn connessione = new DBConn();
            conn=connessione.connect(driverDB[0],connDB[0],userDB[0],passDB[0]);
            conn.setAutoCommit(false);
    
            stmt = conn.createStatement();
    
            rset = stmt.executeQuery(queryDB[0]);
    
            ExportData2CSV csv = new ExportData2CSV();
            csv.ExportData2CSV(rset,filename[0],intestaFile,charSep[0]);
    
                csv.createFileCsv();
            } catch (SQLException e) {
                    e.printStackTrace();
            } catch (IOException e) {
                    e.printStackTrace();
            }
            finally {
                if (stmt != null) {stmt.close();}
                if (conn != null) {conn.close();}
                if (rset != null) {rset.close();}
    
    
    
            }
    
    
        }
    }
    

    이 데이터베이스에 대한 연결의 클래스 DBConn입니다

    import java.sql.*;
    
    /**
     * Created by MAXNIGELNEGRO
     */
    public class DBConn {
        public DBConn() {
        }
        public Connection connect(String driverDB, String db_connect_str, String db_userid, String db_password) {
            Connection conn;
    
            try {
                Class.forName(driverDB).newInstance();
                conn = DriverManager.getConnection(db_connect_str, db_userid, db_password);
    
    
            } catch (Exception e) {
                e.printStackTrace();
                conn = null;
    
            }
            return conn;
        }
    
    
    }
    

    이 결과 집합에 테이블에서 데이터를 검색하기위한 클래스 및 CSV 파일에 기록

    package com.company;
    
    import java.io.FileWriter;
    import java.io.IOException;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    
    /**
     * Created by MAXNIGELNEGRO 
     */
    public class ExportData2CSV {
        public ResultSet rset;
        public String filename;
        public Boolean colomnName;
        public String charSep;
    
        public void ExportData2CSV(ResultSet rset, String filename, Boolean colomnName, String charSep) {
            this.rset = rset;
            this.filename = filename;
            this.colomnName = colomnName;
            this.charSep = charSep;
        }
    
        public void createFileCsv() throws SQLException, IOException {
            FileWriter cname = null;
            try {
    
                    // WRITE COLOMN NAME
                ResultSetMetaData rsmd = rset.getMetaData();
                cname = new FileWriter(filename);
                if (colomnName) {
                    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                        cname.append(rsmd.getColumnName(i));
                        cname.append(charSep);
                        cname.flush();
                    }
                    cname.append(System.getProperty("line.separator"));
                }
    
                // WRITE DATA
                while (rset.next()) {
                    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                        if (rset.getObject(i) != null) {
                            String data = rset.getObject(i).toString().replaceAll(charSep, "");
                            cname.append(data);
                            cname.append(charSep);
                        } else {
                            String data = "null";
                            cname.append(data);
                            cname.append(charSep);
                        }
    
                    }
                    //new line entered after each row
                    cname.append(System.getProperty("line.separator"));
    
                }
    
    
            } catch (Exception e) {
                e.printStackTrace();
    
            } finally {
                if (cname != null) {
                    cname.flush();
                    cname.close();
                }
                if (rset != null) {
                    rset.close();
                }
    
            }
    
        }
    }
    
  6. ==============================

    6.이것은 엑셀 데이터 시트 인

    이것은 엑셀 데이터 시트 인

    레코드를 포함하는 입력 엑셀 안녕하세요이 솔루션은 스레드 2. 출력 스레드 3.data 구조 4.main 1.input 3 개 파일이 필요하다 1.input 넣어 밖으로 SQL을 작성하는 엑셀 출력 스레드를 읽고 스레드 2.data 구조를 보유하고 데이터를 전송하는 것

    (InputThread.java)

        import java.io.*; 
    public class InputThread extends Thread{
    
    
        String fp; 
        InputString is; 
        String tableName="emp"; 
        String outFile;
        InputThread(String FilePath,String nameOfTheTable,String outFileName){
            fp=FilePath;
            outFile=outFileName;
            tableName=nameOfTheTable;
        }
        public void run(){
            File file = new File(fp);
            String line;
            try{
                BufferedReader br = new BufferedReader(new FileReader(file)); 
                if( (line=br.readLine()) != null)
                    is = new InputString(line);
    
                //transform(is);    
    
                InputString tmp = new InputString(createTable(line));
                //tmp.next = is;
                is = tmp;
                //tmp = tmp.next;
    
                for(; (line = br.readLine()) != null; ) {
                    tmp.next = new InputString(line);
                    tmp = tmp.next;
                    transform(tmp); 
                    }               
    
            }catch(Exception e){ System.out.println("Error is :"+e); }
    
            //traverse();
            new OutputThread(is,outFile).start();
        }
        void transform(InputString x){
    
            String[] arr = x.getLine().split(",");
            String sql = "insert into "+tableName+" values(";
            for(int i=0;i<arr.length;i++){
                sql+="'"+arr[i]+"'";
                if( (i+1) < arr.length) sql+=",";
            }
            sql+=");";
            x.setLine(sql);
    
        }
        String createTable(String x){
            String[] arr = x.split(",");
            String sql = "create database vamsidb "+ "use vamsidb "+"create table "+tableName+"(";
            for(int i=0;i<arr.length;i++){
                sql+=arr[i]+" varchar(50)";
                if( (i+1) < arr.length) sql+=",";
            }
            sql+=");";
            return sql;
        }
        /*public void traverse(){
            InputString tmp = is;
            while(is != null){
                System.out.println(is.getLine());
                is=is.next;
            }
        }*/
    
    
    }
    

    (OutputThread.java)

    import java.io.*;
    public class OutputThread extends Thread{
        InputString is;
        String outFile;
        OutputThread(InputString linkedList,String outFileName){
            is=linkedList;
            outFile = outFileName;
        }
        public void run(){
    
            try{
                FileOutputStream fos = new FileOutputStream(outFile);
                while(is != null){              
                    fos.write(is.getLine().getBytes());             
                    is=is.next;
                }
                fos.close();
            }catch(Exception e){
                System.out.println("Error is :"+e);
             }
        }
    }
    

    (Main.java)

    public class Main{
    public static void main(String[] args){
    
            InputThread it = new InputThread("sasken.csv","emp","output.sql");
    
            it.start();     
        }
    }
    

    (Data Structure.java)

    //이 클래스 길게 입력 변환 데이터 구조를 나타낸다 SQL 문의 링크 된 목록으로 // 데이터

    class InputString{
    
        String line;
        InputString next;
    
        InputString(String x){
            line = x;
        }
        String getLine(){
            return line;
        }   
        void setLine(String x){
            line = x;
        }
    }
    

    출력 결과

  7. ==============================

    7.당신은 자바 DB에서 레코드를 가져 오기 위해 JDBC를 사용하고 CSV / Excel로 데이터를 내보내는 아파치 POI를 사용할 수 있습니다.

    당신은 자바 DB에서 레코드를 가져 오기 위해 JDBC를 사용하고 CSV / Excel로 데이터를 내보내는 아파치 POI를 사용할 수 있습니다.

    또한, 당신은 당신의 기본 이메일 클라이언트를 사용하여 이메일을 보내 자바의 데스크탑 API를 사용할 수 있습니다.

  8. ==============================

    8.이 작업을 위해 당신은 작업 쓰기 모든 쿼리 및 드라이버를 차지 할 수있는 작은 코드가 필요합니다. 첫 번째 입력은 사용자가 작성하는 소프트웨어의 입력으로 드라이버 이름이어야합니다. 그런 다음 작성중인 소프트웨어는 주어진 어떤 SQL을 실행하고 단지 행과 열을 제공 할 수있는 위치에 있어야합니다.

    이 작업을 위해 당신은 작업 쓰기 모든 쿼리 및 드라이버를 차지 할 수있는 작은 코드가 필요합니다. 첫 번째 입력은 사용자가 작성하는 소프트웨어의 입력으로 드라이버 이름이어야합니다. 그런 다음 작성중인 소프트웨어는 주어진 어떤 SQL을 실행하고 단지 행과 열을 제공 할 수있는 위치에 있어야합니다.

    다음 작업은 자바 응용 프로그램의 JDBC에서 유래 된 ResultSet을 구문 분석 온다. 어느 쪽이든 당신은 당신이 할 수있는 자바 API가 얼마나 좋은 기반으로 CSV 파일 또는 엑셀로 결과를 쓰고 싶어요.

    는 CVS에 출력을 작성하는 것은 쉽고 trival 없습니다. 나는 Excel로 데이터를 내보낼에 근무하지 않았습니다. 나는 당신이 그것에 대해 단지를 찾을 수입니다.

  9. ==============================

    9.예!

    예!

    당신은 JDBC를 사용하여 다른 데이터베이스 유형에 연결 한 다음 결과 (여기에서 보이는)와 엑셀을 만들 수 있습니다.

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class TestAccessExcel {
      public static Connection getConnection() throws Exception {
        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        String url = "jdbc:odbc:excelDB";
        String username = "username";
        String password = "pass";
        Class.forName(driver);
        return DriverManager.getConnection(url, username, password);
      }
    
      public static void main(String args[]) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
          conn = getConnection();
          stmt = conn.createStatement();
          String excelQuery = "select * from [Sheet1$]";
          rs = stmt.executeQuery(excelQuery);
    
          while (rs.next()) {
            System.out.println(rs.getString("BadgeNumber") + " " + rs.getString("FirstName") + " "
                + rs.getString("LastName"));
          }
        } catch (Exception e) {
          System.err.println(e.getMessage());
        } finally {
          try {
            rs.close();
            stmt.close();
            conn.close();
    
          } catch (SQLException e) {
            e.printStackTrace();
          }
        }
      }
    }
    
  10. ==============================

    10.이 솔루션은 특성 파일을 기반으로합니다. 이 옵션은 구성되는 경우 :

    이 솔루션은 특성 파일을 기반으로합니다. 이 옵션은 구성되는 경우 :

    이 과정은 동시에 4 개 테이블을 다운로드 4 개 스레드 비스 시작할 수 있습니다. 다시 실행하려는 경우, 생성 된 파일을 삭제해야합니다. 프로세스 데이터를 텍스트 파일 (logs.txt)도 생성됩니다.

    ---- 법안 FILE : 수출 Properties.prop --------- 이 솔루션의 초안 구성 버전을 작성합니다 :

    C : \ TMP \ 테스트 \ ExportProperties.prop

    ## configuration properties
    driver=oracle.jdbc.driver.OracleDriver
    url=jdbc:oracle:thin:@ldap://localhost
    username=user
    password=pass
    fileExtension=_20200623.csv
    columSeparator=;
    charsetName=CP1252
    ## export only 10 rows change to false
    only10Rows=true
    ##tables
    tableName.1=USER
    tableName.1.sqlWhere= user.name IS NOT NULL
    tableName.2=ROLL
    tableName.3=FIRMA
    

    --------- 주요 파일 --------

    public class ExportTable2CSVMain implements Runnable {
        static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS|");
        static final String folder = "C:\\tmp\\test\\";
        static final Properties prop = getProperties();
    
        public static void main(String[] args) {
            for (int x = 1; x < 6; x++) {
                try {
                    writieLog(0, "Start thread " + x);
                    new ExportTable2CSVMain();
                    Thread.sleep(1000);
                } catch (final Exception e) {
                    e.printStackTrace();
                }
            }
        }
    
        public ExportTable2CSVMain() {
            final Thread t = new Thread(this);
            t.start(); // start the thread -> run
        }
    
        @Override
        public void run() {
            int pos = 1;
            String tableName = prop.getProperty("tableName." + pos);
            while (tableName != null) {
                try {
                    export(tableName, pos++);
                } catch (final Exception e) {
                    e.printStackTrace();
                }
                tableName = prop.getProperty("tableName." + pos);
            }
        }
    
        private void export(String tableName, int filePos) throws Exception {
            final boolean only10Rows = prop.getProperty("only10Rows", "false").equals("true");
            String extraWhere = prop.getProperty("tableName."+filePos+".sqlWhere");
            if(extraWhere ==null)
                extraWhere = prop.getProperty("sqlWhere");
            if(extraWhere ==null)
                extraWhere = "";
            final String sql = "select * from " + tableName + extraWhere
                    + (only10Rows ? " FETCH NEXT 10 ROWS ONLY" : "");
            final String fileName = folder + tableName + prop.getProperty("fileExtension");
            Connection conn = null;
            Statement stmt = null;
            ResultSet rs = null;
            ExportTable2CSV data2csv = null;
            try {
                data2csv = new ExportTable2CSV(fileName, tableName, filePos);
                if (data2csv.toDo()) {
                    conn = getConnection();
                    stmt = conn.createStatement();
                    rs = stmt.executeQuery(sql);
                    data2csv.createFileCsv(rs);
                }
            } catch (final Exception e) {
                final int row = data2csv == null ? -1 : data2csv.row;
                writieLog(filePos, "SQL", "Error", "rows:" + row, tableName, e.getMessage());
                e.printStackTrace();
            } finally {
                try {
                    rs.close();
                } catch (final Exception e) {
                }
                try {
                    stmt.close();
                } catch (final Exception e) {
                }
                try {
                    conn.close();
                } catch (final Exception e) {
                }
            }
        }
    
        public Connection getConnection() throws Exception {
            Class.forName(prop.getProperty("driver"));
            return DriverManager.getConnection(//
                    prop.getProperty("url"),
                    prop.getProperty("username"),
                    prop.getProperty("password"));
        }
    
        static private Properties getProperties() {
            File file = new File(folder);
            if (!file.exists()) { // if the folder do not exist create it 
                file.mkdirs();
            }
            file = new File(folder + "ExportProperties.prop");
            if (!file.exists()) {
                try {
                    final PrintWriter out = new PrintWriter(
                            new BufferedWriter(new FileWriter(folder + "ExportProperties.prop", true)));
    
                    out.println(//
                            "## configuration properties\n" +
                                    "driver=oracle.jdbc.driver.OracleDriver\n" +
                                    "url=jdbc:oracle:thin:@ldap://localhost\n"+
                                    "username=USER\n" +
                                    "password=PASSWORD\n" +
                                    "sqlWhere=\n" +
                                    "fileExtension=_20200619.csv\n" +
                                    "columSeparator=;\n" +
                                    "charsetName=CP1252\n" +
                                    "##tables\n" +
                                    "tableName.1=USER\n" + //
                                    "tableName.2=ROLL\n" 
                    );
                    out.close();
                } catch (final Exception e) {
                    e.printStackTrace();
                }
            }
            final Properties prop = new Properties();
            try {
                prop.load(new FileInputStream(folder + "ExportProperties.prop"));
            } catch (final IOException e) {
                e.printStackTrace();
            }
            return prop;
        }
    
        public static void writieLog(int filePos, String... txt) throws Exception {
            final PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(folder + "logs.txt", true)));
            String sb = "";
            sb += formatter.format(new Date()) + "\t";
            sb += filePos == 0 ? "" : "F-" + filePos + "\t";
            for (final String s : txt) {
                sb += s + "\t";
            }
            System.out.println(sb);
            out.println(sb);
            out.close();
        }
    }
    

    ---------------- ExportTable2CSV 파일 -------

    /**
     * Created by Jose Manuel Davila (Mel) kailas.mel@gmail.com
     */
    public class ExportTable2CSV {
        final String fileName;
        final String table;
        final String columSeparator;
        final Boolean colomnName = true;
        final int filePos;
        int row = 0;
        int column = 0;
    
        public ExportTable2CSV(String fileName, String table, int filePos) {
            this.filePos = filePos;
            this.fileName = fileName;
            this.table = table;
            columSeparator = ExportTable2CSVMain.prop.getProperty("columSeparator", ";");
        }
    
        public boolean toDo() throws Exception {
            if (new File(fileName).exists()) {// the file exist jet return
                return false;
            }
            writeLine("");
            return true;
        }
    
        public void createFileCsv(ResultSet rs) throws Exception {
            String sb = "";
            try {
                ExportTable2CSVMain.writieLog(filePos, "FILE", "INI ", table, fileName);
                // WRITE COLOMN NAME
                final ResultSetMetaData rsmd = rs.getMetaData();
                sb = "";
                final List<String> list = new ArrayList<String>();
                if (colomnName) {
                    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                        sb += rsmd.getColumnName(i) + columSeparator;
                        list.add(rsmd.getColumnName(i));
                    }
                    writeLine(sb.toString());
                }
                // WRITE DATA
                while (rs.next()) {
                    sb = "";
                    column = 0;
                    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                        final Object obj = rs.getObject(i);
                        String data = "";
                        if (obj != null) {
                            if (obj instanceof String) {
                                data = obj.toString();
                                if (data.indexOf(columSeparator) != -1) {
                                    if (data.indexOf("\"") != -1) {
                                        data = data.replaceAll("\"", "'");
                                        ExportTable2CSVMain.writieLog(filePos, "FILE", "WITH comm and ; ", "row:" + row,
                                                "Column:" + list.get(column), table, fileName);
                                    }
                                    data = "\"" + data + "\"";
                                }
                            } else {
                                data = obj.toString();
                            }
                        }
                        sb += data + columSeparator;
                        column++;
                    }
                    writeLine(sb.toString());
                    row++;
                }
                ExportTable2CSVMain.writieLog(filePos, "FILE", "END ", "rows:" + row, table, fileName);
            } catch (final Exception e) {
                ExportTable2CSVMain.writieLog(filePos, "FILE", "Error ", "rows:" + row, table, fileName, e.getMessage());
                e.printStackTrace();
            } finally {
                if (rs != null) {
                    rs.close();
                }
            }
        }
    
        void writeLine(String line) throws Exception {
            if (row > 0 && row % 1000 == 0) {
                System.out.println(filePos + " " + row + " working ...");
            }
            final PrintWriter cname = new PrintWriter(new BufferedWriter((new OutputStreamWriter(
                    new FileOutputStream(fileName, true), ExportTable2CSVMain.prop.getProperty("charsetName", "CP1252")))));
            if (line.equals("")) {
                cname.print(line);
            } else {
                cname.println(line);
            }
            cname.close();
        }
    }
    

    --------- POM 파일의 pom.xml ----------------

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>ExportTable2CSV</groupId>
      <artifactId>ExportTable2CSV</artifactId>
      <version>1.1.0</version>
      <name>ExportTable2CSV</name>
      <properties>
            <ojdbc8.version>18.3.0.0.0</ojdbc8.version>
      </properties>
    
      <dependencies>
            <dependency>
                <groupId>com.oracle</groupId>
                <artifactId>ojdbc8</artifactId>
                <version>${ojdbc8.version}</version>
                <scope>runtime</scope>
            </dependency>
      </dependencies>
    </project>
    

    탭으로 구분 된 열을 내 보냅니다.

    등록 정보 파일이 소품을 변경 :

    fileExtension=_mel.txt
    columSeparator=\t
    
  11. from https://stackoverflow.com/questions/8563376/exporting-sql-query-result-to-csv-or-excel by cc-by-sa and MIT license