简体   繁体   中英

How do I create separate output file for each sql record?

public void selectdata(Connection conn, String database){

    String table = "Mo";  // using Mo table,
    String comandoSql = "SELECT * FROM " + database + "."+"dbo"+ "."+ table;
    try {
        stmt = conn.createStatement();  

        rs = stmt.executeQuery(comandoSql);
        System.out.println("Command sql: ");
        while (rs.next()) {
            String DocumentName = rs.getString(2); 
            doc1 = DocumentName;
            try {

                File file = new File("///.txt");  // path to output folder.
                FileWriter fileWritter = new FileWriter(file,true);
                BufferedWriter out = new BufferedWriter(fileWritter);
                out.write(doc1);
                out.newLine();
                out.close();

                  } catch (IOException e1) {
              System.out.println("Could not write in the file");
            } 
          }
    } catch (SQLException e) {
            e.printStackTrace();
    }  

this generates the output file but contains all the records in one file, my problem is how to generate separate file for each record don't want to do the post process in order to generate the separate files? any help?????? not fancy for scanner, because don't know how many lines will be in one record(it is a kind of multiple documents which stored into database table!!!!)

Just create a new file for each record:

 int counter = 0;

 while (rs.next()) {
        String DocumentName = rs.getString(2); 
        doc1 = DocumentName;
        try {

            File file = new File("///" + counter + ".txt");  // path to output folder.
            FileWriter fileWritter = new FileWriter(file,true);
            BufferedWriter out = new BufferedWriter(fileWritter);
            out.write(doc1);
            out.newLine();
            out.close();
            counter++;

              } catch (IOException e1) {
          System.out.println("Could not write in the file");
        } 
      }

Just create a counter variable or something to differentiate each file. Append the counter to the file name so it will create a new file for each record...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM