如何获取CSVPrinter调用printRecords后写入的记录行数?
问题描述
我执行了一条SELECT语句,通过单次调用CSVPrinter.printRecords(resultSet)把整个ResultSet保存到文件里,这个方法运行正常,但我没法直接知道写入了多少条记录——它本身没有返回值,这点挺不方便的。
我试过打印后调用resultSet.getRow(),但它一直返回0;也试过先调用resultSet.last()再用getRow(),但我的结果集是forward only类型,这个操作失败了,afterLast()也因为同样原因用不了。
我知道可以自己遍历结果集,逐行传给CSVPrinter同时计数,但这种方式不够简洁。有没有更方便的办法?
更新:已经提交了改进请求。
解决方案
目前CSVPrinter.printRecords(ResultSet)确实没有返回记录数的设计,在官方修复之前,有几个实用的替代思路:
自定义ResultSet包装类统计行数
实现一个包装类代理原ResultSet,在next()方法被调用时累加计数,再把包装后的对象传给printRecords。示例代码如下:class CountingResultSet implements ResultSet { private final ResultSet delegate; private int count = 0; public CountingResultSet(ResultSet delegate) { this.delegate = delegate; } @Override public boolean next() throws SQLException { boolean hasNext = delegate.next(); if (hasNext) { count++; } return hasNext; } // 其他所有ResultSet方法直接委托给原对象,示例: @Override public String getString(String columnLabel) throws SQLException { return delegate.getString(columnLabel); } // 省略其余ResultSet方法的委托实现... public int getCount() { return count; } }使用方式:
CountingResultSet countingRs = new CountingResultSet(originalResultSet); csvPrinter.printRecords(countingRs); int recordCount = countingRs.getCount();这种方式保留了
printRecords的简洁性,同时能准确拿到实际写入的记录数。提前查询总行数(需注意数据一致性)
修改SQL逻辑,先执行SELECT COUNT(*) FROM ...(确保过滤条件和原查询完全一致)获取总行数,再执行原查询导出CSV。但要注意两次查询之间如果数据发生变更,计数和实际导出行数可能存在差异。封装遍历计数逻辑为工具方法
把遍历、打印、计数的逻辑封装成工具方法,后续调用只需一行代码:public static int printRecordsWithCount(CSVPrinter printer, ResultSet rs) throws SQLException, IOException { int count = 0; while (rs.next()) { printer.printRecord(rs); count++; } printer.flush(); return count; }调用时:
int count = printRecordsWithCount(csvPrinter, resultSet);
内容的提问来源于stack exchange,提问作者Mikhail T.

