有没有办法从数据库中获取记录作为逗号分隔的文本文件

Is there any way to get records from a database as a comma seperated text file

朋友们, 我一直坚持这份工作 我有一个 table empdb 有 1000 行,如下所示

 id    name     desgn
 ---  -------  ----------------
  1   Mike     Analyst
  2   Jim      Manager
  3   John     Engg

等等。等等

我想编写一个 servlet 来查询这个 table 并以文本格式下载 "emp_info.txt" 如下所示

 1,sam,Engg
 2,Mike,Excecutive
 3,Jim,Manager

我的意思是数据库中的每条记录都应该在单独的行上

请指导

我们无法直接从数据库获取记录作为 csv 文件,有许多第三方库可用于处理 CSV 文件,

让我们来看看其中的几个:

  • Open CSV:另一个受欢迎且积极维护的 CSV 库
  • Apache Commons CSV:Apache 用于处理 CSV 文件的 CSV 产品
  • Flatpack:正在积极开发的开源 CSV 库
  • CSVeed:开源且积极维护。

Sample code for open csv, add your open csv jar to you class path. create one csv file and add its location to the code below

File file = new File(filePath); 
    try { 
        // create FileWriter object with file as parameter 
        FileWriter outputfile = new FileWriter(file); 

        // create CSVWriter object filewriter object as parameter 
        CSVWriter writer = new CSVWriter(outputfile); 

        // adding header to csv 
        String[] header = { "id", "name", "design" }; 
        writer.writeNext(header); 

        // add data to csv 
       // in loop
        String[] data = {}
        writer.writeNext(data); 

       // execute this two line until your data remains. 

        // closing writer connection 
        writer.close(); 
    } 
    catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
    } 

After creating the file set content type as csv and flush the buffer the browser will download the file for end user.

                    resp.setContentType("application/csv");
                    resp.setHeader(HttpHeaders.CONTENT_DISPOSITION, file);
                    inStrm = new FileInputStream(file);
                    FileCopyUtils.copy(inStrm, resp.getOutputStream());
                    resp.flushBuffer();

我假设您希望访问您的网络应用程序的用户能够将此 "empdb" 数据库 table 中的所有数据下载为 "emp_info.txt" 文件。只是为了清楚什么是 servlet:

Servlet - resides at server side and generates a dynamic web page

您应该将此任务分成不同的部分:

  1. 使用 JPA 和 e.x Hibernate 将您的数据库与 java 应用程序连接起来,同时实现一个存储库。
  2. 创建将用户存储库从 table 和 write it to .txt file.
  3. 中获取所有数据的服务
  4. 在 GUI 中实现按钮或其他功能,这将使用您创建的服务并为用户发送文件。