如何将从数据库中获取的值存储到文本文件中

How to store fetched values from database into a text file

我需要你的帮助来将从数据库中获取的值存储到文本文件中 (Sample.txt)。每个获取的行都应存储在文本文件中并以换行符分隔。在每个检索到的列之后,它应该用一行“|”分隔,所以我需要你的帮助。这是代码:

public void GenerateTXT() {
   Connection conn = null;
   Statement stmt = null;
   try{
      Class.forName("com.mysql.jdbc.Driver");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      stmt = conn.createStatement();

      String sql = "SELECT id, name, amount FROM Employee";
      ResultSet rs = stmt.executeQuery(sql);
      while(rs.next()){
         int id  = rs.getInt("id");
         int age = rs.getString("name");
         String first = rs.getInt("amount");
          }
      rs.close();
   }catch(SQLException se){
      se.printStackTrace();
   }catch(Exception e){
      e.printStackTrace();
   }finally{
      try{
         if(stmt!=null)
            conn.close();
      }catch(SQLException se){
      }
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }
   }
}
}

您可以使用下面的代码。

public void GenerateTXT() { 
   Connection conn = null;
   Statement stmt = null;
   try{ 
      Class.forName("com.mysql.jdbc.Driver");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      stmt = conn.createStatement();

      File file = new File("/path/to/file/filename.txt");

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);

      String sql = "SELECT id, name, amount FROM Employee";
      ResultSet rs = stmt.executeQuery(sql);

      while(rs.next()){
         int id  = rs.getInt("id");
         int age = rs.getString("name");
         String first = rs.getInt("amount");
         bw.append(id+"|"+age+"|"+first+"\n");
          } 
      rs.close();
      bw.close();
   }catch(SQLException se){ 
      se.printStackTrace(); 
   }catch(Exception e){
      e.printStackTrace();
   }finally{ 
      try{ 
         if(stmt!=null)
            conn.close();
      }catch(SQLException se){ 
      } 
      try{ 
         if(conn!=null)
            conn.close();
      }catch(SQLException se){ 
         se.printStackTrace(); 
      } 
   } 
} 
}