2017-05-04 71 views
-1

我需要當我使用opencsv轉換結果設定爲CSV任何數據庫(不只是Postgres的)正在創建opencsv創建空的CSV

空csv文件。

這裏是doGet方法的在servlet代碼:

final String JDBC_DRIVER = "org.postgresql.Driver"; 
    final String DB_URL = "jdbc:postgresql://localhost:5432/postgres"; 

    // Database credentials 
    final String USER = "postgres"; 
    final String PASS = "12345"; 

    response.setContentType("text/html"); 

    PrintWriter out = response.getWriter(); 

    String title = "Database Result"; 
    String docType = 
      "<!doctype html public \"-//w3c//dtd html 4.0 " + 
        "transitional//en\">\n"; 
    out.println(docType + 
      "<html>\n" + 
      "<head><title>" + title + "</title></head>\n" + 
      "<body bgcolor=\"#f0f0f0\">\n" + 
      "<h1 align=\"center\">" + title + "</h1>\n"); 

    PreparedStatement ps = null; 
    Connection conn = null; 

    try { 
     // Register JDBC driver 
     Class.forName("org.postgresql.Driver"); 

     // Open a connection 
     conn = DriverManager.getConnection(DB_URL, USER, PASS); 

     // Execute SQL query 
     //stmt = conn.createStatement(); 
     String sql = "SELECT * FROM users"; 

     ps = conn.prepareStatement(sql, 
       ResultSet.TYPE_SCROLL_SENSITIVE, 
       ResultSet.CONCUR_UPDATABLE); 

     ResultSet rs = ps.executeQuery(); 

     /*if(rs.next()){ 
      System.out.println("Name = "+rs.getString("first_name")); 
     }*/ //prints name so rs is not empty 

     //rs.first(); 
     CSVWriter writer = new CSVWriter(new FileWriter("Test.csv")); 
     //even tried with seperator '\t' or ',' 
     writer.writeAll(rs, true); 
     writer.close(); 
     out.println("</body></html>"); 

     // Clean-up environment 
     rs.close(); 
     ps.close(); 
     conn.close(); 
     } catch (SQLException se) { 
      //Handle errors for JDBC 
      se.printStackTrace(); 
     } catch (Exception e) { 
      //Handle errors for Class.forName 
      e.printStackTrace(); 
     } finally { 
      //finally block used to close resources 
      try { 
       if (ps != null) 
        ps.close(); 
      } catch (SQLException se2) { 
      }// nothing we can do 
      try { 
       if (conn != null) 
        conn.close(); 
      } catch (SQLException se) { 
       se.printStackTrace(); 
      }//end finally try 
     } //end try 

不知道有什麼錯誤。試過不同的方式,但csv總是空的。即使嘗試了writer.flush(),rs.beforeFirst(),rs.first()也沒有任何效果。

回答

0

是你的問題,你沒有看到數據的HTML - 如果是這樣的話,而不是在CSVWriter中創建一個新的FileWriter只是傳入你的變量。

還是你檢查Test.csv和文件,沒有什麼?如果是,則首先通過在executeQuery後面添加以下內容來檢查結果集中是否實際存在數據:

rs.last(); 
long numberOfRecords = rs.getRow(); 
rs.beforeFirst(); 
System.out.println("Number of Users in table is: " + numberOfRecords);