Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 859
Harish Vangavolu Avatar asked Jul 24 '14 21:07

Harish Vangavolu


People also ask

How do I get all columns from ResultSet?

You can get the column count in a table using the getColumnCount() method of the ResultSetMetaData interface. On invoking, this method returns an integer representing the number of columns in the table in the current ResultSet object.

What is the right way to get the numbers data using ResultSet object in JDBC?

We can use getX() method to get the data of the columns while iterating through the results where X – is the datatype of the column. We can use either Column Names or Index to get the values using getX() methods. We can also mention index number of the Column instead of Column Name in the getX() methods.


1 Answers

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);      } 
like image 95
Adarsh Avatar answered Oct 09 '22 14:10

Adarsh