【问题标题】:How to store fetched values from database into a text file如何将从数据库中获取的值存储到文本文件中
【发布时间】:2016-01-10 07:01:36
【问题描述】:

我需要您的帮助,将从数据库中提取的值存储到文本文件 (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();
      }
   }
}
}

【问题讨论】:

  • 您是在问如何将结果打印到文件中,或者如何更正您的数据库查询?如果是后者,对我来说似乎找到了;如果是前者,那么这个问题很可能是重复的。

标签: java file text file-io text-files


【解决方案1】:

你可以使用下面的代码。

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(); 
      } 
   } 
} 
} 

【讨论】:

  • 很高兴能帮上忙! :)
猜你喜欢
  • 1970-01-01
  • 2018-03-20
  • 1970-01-01
  • 2012-10-27
  • 2023-03-26
  • 2013-08-12
  • 2012-10-31
  • 2021-07-10
  • 2019-01-15
相关资源
最近更新 更多