Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

java - How do you get values from all columns using ResultSet.getBinaryStream() in jdbc?

How do I to write an entire table to a flat file (text file) using jdbc? So far I've attempted the following:

Statement statement = connection.createStatement();
   ResultSet result = statement.executeQuery("SELECT * FROM tablename");
   BufferedInputStream buffer;
   FileOutputStream out = new FileOutputStream("flatfile.txt");
   while(result.next() )
   {
      buffer =  new BufferedInputStream(result.getBinaryStream("????") );
      byte[] buf = new byte[4 * 1024]; //4K buffer
      int len;
      while( (len = buffer.read(buf, 0, buf.length) ) != -1 )
      {
          out.write(buf, 0, len );
      }
   }
   out.close();

"????" is just my placeholder. I am stuck on what to pass in as an argument.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can get all the column names and the entire data from your table using the code below. writeToFile method will contain the logic to writing to file (if that was not obvious enough :) )

    ResultSetMetaData metadata = rs.getMetaData();
    int columnCount = metadata.getColumnCount();    
    for (int i = 1; i <= columnCount; i++) {
        writeToFile(metadata.getColumnName(i) + ", ");      
    }
    System.out.println();
    while (rs.next()) {
        String row = "";
        for (int i = 1; i <= columnCount; i++) {
            row += rs.getString(i) + ", ";          
        }
        System.out.println();
        writeToFile(row);

    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...