Save SqlQuery result to FlatFiles

Posted by Somesh Shinde On Wednesday, 17 August 2016 0 comments

Save SqlQuery result to FlatFiles


 public void printToFile( ResultSet rs, String path ) throws IOException { 

     PrintStream out = new FileOutputStream( path );

     int cols = rs.getMetaData().getColumnCount();

     while( rs.next() ) { 
         for( int i = 0; i < cols ; i++ ) { 
             out.printf("%s,", rs.getObject( i ) );
          }           
          out.println();
     }

     // add exception handling and such...
     // or move the from here.
     out.close();
     rs.close();

 }
And then call it like this:
 ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
 printToFile( rs, "/some/file" );


If you use this function, be sure to change 
PrintStream out = new FileOutputStream(path); toPrintStream out = new PrintStream(new FileOutputStream(pat‌​h));

0 comments:

Post a Comment