I need a Java function that returns the results of a SQL SELECT query as an InputStream parameter for another system that sends the result over a network.
However, the InputStream must be of a String with custom delimiters (i.e. often, but not always, CSV).
While I can easily create a function to retrieve the result, create a delimited String, and finally convert that String to an InputStream, the SQL result will often be much too large to process in memory. Also, processing the entire result set before returning the result will incur an unwanted wait time.
How can I return an InputStream to iterate over the SQL result and send the processed (delimited) data as it is returned from the database?
Posting (not tested) code snippet, which should give you basic idea:
This is very straight-forward implementation and it can be improved in following ways:
new byte[]is costly operation), more sophisticated logic can be implemented to use byte array buffer which is initialised only once and then re-filled. One then should changeRowToByteArrayConverter.rowToByteArraymethod’s signature toint fillByteArrayFromRow(ResultSet rs, byte[] array)which should return number of bytes filled and fill passed byte array.Because byte array contains signed bytes it can contain
-1(which is actually255as unsigned byte) and thus indicate incorrect end of stream, so& (0xff)is used to convert signed byte to unsigned bytes as integer values. For details refer to How does Java convert int into byte?.Please also note that if network transfer speed is slow, this may keep open result sets for
a long time, thus posing problems for the database.
Hope this helps …