VOOZH about

URL: https://www.javacodegeeks.com/2018/12/java-streaming-jdbc-resultset-csv.html

⇱ Java: Streaming a JDBC ResultSet as CSV - Java Code Geeks


In my previous post, I showed how to convert a java.sql.ResultSet to JSON and stream it back to the caller. This post, is about streaming it in CSV format instead. Streaming allows you to transfer the data, little by little, without having to load it all into the server’s memory.

For example, consider the following ResultSet:

+---------+-----+
| Name | Age |
+---------+-----+
| Alice | 20 |
| Bob | 35 |
| Charles | 50 |
+---------+-----+

The corresponding CSV is:

name,age
Alice,20
Bob,35
Charles,50

The following class (also available in my GitHub Repository) can be used to convert the ResultSet to CSV. Note that this class implements Spring’s ResultSetExtractor, which can be used by a JdbcTemplate to extract results from a ResultSet.

/**
 * Streams a ResultSet as CSV.
 */
public class StreamingCsvResultSetExtractor
 implements ResultSetExtractor<Void> {

 private static char DELIMITER = ',';

 private final OutputStream os;

 /**
 * @param os the OutputStream to stream the CSV to
 */
 public StreamingCsvResultSetExtractor(final OutputStream os) {
 this.os = os;
 }

 @Override
 public Void extractData(final ResultSet rs) {
 try (var pw = new PrintWriter(os, true)) {
 final var rsmd = rs.getMetaData();
 final var columnCount = rsmd.getColumnCount();
 writeHeader(rsmd, columnCount, pw);
 while (rs.next()) {
 for (var i = 1; i <= columnCount; i++) {
 final var value = rs.getObject(i);
 pw.write(value == null ? "" : value.toString());
 if (i != columnCount) {
 pw.append(DELIMITER);
 }
 }
 pw.println();
 }
 pw.flush();
 } catch (final SQLException e) {
 throw new RuntimeException(e);
 }
 return null;
 }

 private static void writeHeader(final ResultSetMetaData rsmd,
 final int columnCount, final PrintWriter pw) throws SQLException {
 for (var i = 1; i <= columnCount; i++) {
 pw.write(rsmd.getColumnName(i));
 if (i != columnCount) {
 pw.append(DELIMITER);
 }
 }
 pw.println();
 }
}

To use this in a web service with JAX-RS:

import javax.ws.rs.core.StreamingOutput;

@GET
@Path("runQuery")
@Produces("text/csv")
public StreamingOutput runQuery() {
 return new StreamingOutput() {
 @Override
 public void write(final OutputStream os)
 throws IOException, WebApplicationException {
 jdbcTemplate.query("select name, age from person",
 new StreamingCsvResultSetExtractor(os));
 }
 };
}

Related posts:

Streaming a JDBC ResultSet as JSON

Published on Java Code Geeks with permission by Fahd Shariff, partner at our JCG program. See the original article here: Java: Streaming a JDBC ResultSet as CSV

Opinions expressed by Java Code Geeks contributors are their own.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

πŸ‘ Photo of Fahd Shariff
Fahd Shariff
December 29th, 2018Last Updated: December 24th, 2018
0 3,325 1 minute read

Fahd Shariff

Fahd is a software engineer working in the financial services industry. He is passionate about technology and specializes in Java application development in distributed environments.
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button
Close
wpDiscuz