import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class TestMemoryIssue {

  public static void main(String[] args) throws Throwable {
    String sql = "SELECT b FROM public.a";
    try (Connection connection =
        DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/postgres?currentSchema=public", "username", "password")) {
      connection.setAutoCommit(false);
      try (PreparedStatement ps = connection.prepareStatement(sql)) {
        ps.setFetchSize(5); // we do not want to run out of Java heap space
        try (ResultSet rs = ps.executeQuery()) {
          int i = 0;
          while (rs.next()) {
            // just loop over all data, get the data and do something with it
            i++;
            byte[] b = rs.getBytes(1);
            if (i % 10 == 0 || b == null || b.length <= i) {
              System.err.println("Row " + i + ": " + (b != null ? b.length : null));
            }
          }
        }
      }
    }
  }
}
