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.
result.getBinaryStream("????")
will only return for the value for that column as you put as placeholder.If you want to get all the column, you need to use
ResultSetMetaData
fromResultSet
Here's how I dump a table from a JDBC connection, very useful for debugging if you want to see all rows that are in an in memory (ex: HSQL) DB for instance:
output is like
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 :) )