1 回答
TA贡献1836条经验 获得超5个赞
基本上这不能在DbUtils开箱即用的情况下完成。我摆脱了QueryRunner并且MapListHandler因为处理程序创建了一个ArrayList. 我不是基于拉,而是基于推,创建了一个非常相似的方法MyQueryRunner,它需要 aMyRowHandler而不是返回一个集合,而是迭代ResultSet并调用我的输出函数。
我确信有更优雅的方法可以做到这一点并返回某种行缓冲区,但这是我需要的 80/20 并且适用于大型数据集。
行处理程序
public class RowHandler {
private static final RowProcessor ROW_PROCESSOR = new BasicRowProcessor();
private JsonLOutputWriter writer;
public RowHandler(JsonLOutputWriter writer) {
this.writer = writer;
}
int handle(ResultSet rs) throws SQLException {
AtomicInteger counter = new AtomicInteger();
while (rs.next()) {
writer.writeRow(this.handleRow(rs));
counter.getAndIncrement();
}
return counter.intValue();
}
protected Map<String, Object> handleRow(ResultSet rs) throws SQLException {
return this.ROW_PROCESSOR.toMap(rs);
}
}
查询处理程序
class CustomQueryRunner extends AbstractQueryRunner {
private final RowHandler rh;
CustomQueryRunner(DataSource ds, StatementConfiguration stmtConfig, RowHandler rh) {
super(ds, stmtConfig);
this.rh = rh;
}
int query(String sql) throws SQLException {
Connection conn = this.prepareConnection();
return this.query(conn, true, sql);
}
private int query(Connection conn, boolean closeConn, String sql, Object... params)
throws SQLException {
if (conn == null) {
throw new SQLException("Null connection");
}
PreparedStatement stmt = null;
ResultSet rs = null;
int count = 0;
try {
stmt = this.prepareStatement(conn, sql);
this.fillStatement(stmt, params);
rs = this.wrap(stmt.executeQuery());
count = rh.handle(rs);
} catch (SQLException e) {
this.rethrow(e, sql, params);
} finally {
try {
close(rs);
} finally {
close(stmt);
if (closeConn) {
close(conn);
}
}
}
return count;
}
}
添加回答
举报