![](/img/trans.png)
[英]How to use OutputStream within try-with-resources properly?
[英]How to properly use try-with-resources in Database connection?
我环顾四周,但似乎无法找到我的问题的答案。
这是上下文:我必须在我的 Java 程序中连接到数据库并执行一个我无法控制且事先不知道的 SQL 请求。 为此,我使用下面的代码。
public Collection<HashMap<String, String>> runQuery(String request, int maxRows) {
List<HashMap<String, String>> resultList = new ArrayList<>();
DataSource datasource = null;
try {
Context initContext = new InitialContext();
datasource = (DataSource) initContext.lookup("java:jboss/datasources/xxxxDS");
} catch (NamingException ex) {
// throw something.
}
try (Connection conn = datasource.getConnection();
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(request); ) {
while (rs.next())
{
HashMap<String, String> map = new HashMap<>();
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
map.put(rs.getMetaData().getColumnName(i).toUpperCase(), rs.getString(i));
}
resultList.add(map);
}
} catch (SQLException ex) {
// throw something.
}
return resultList;
}
我面临的问题是:如您所见,还有一个我没有使用的参数maxRows
。 我需要在statement
指定这一点,但不能在try-with-resources
。
我想通过在第一个try-with-resources
嵌套另一个try-with-resources
以指定最大行数(如本代码示例中所示)来避免增加此方法的认知复杂性。
try (Connection conn = datasource.getConnection();
Statement statement = conn.createStatement(); ) {
statement.setMaxRows(maxRows);
try (ResultSet rs = statement.executeQuery(request); ) {
while (rs.next())
{
HashMap<String, String> map = new HashMap<>();
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
map.put(rs.getMetaData().getColumnName(i).toUpperCase(), rs.getString(i));
}
resultList.add(map);
}
}
} catch (SQLException ex) {
// throw something.
}
有没有办法只用一个try-with-resources
来做到这一点?
如果您可以采用其他方法,那么只需一个 try-resources 即可
而不是Statement statement = conn.createStatement();
Statement statement = createStatement(conn, maxRows);
在该新方法中,创建 Statement 对象并设置 maxRows 并返回语句 obj。
您可以添加一个辅助方法来在单个 try-with-resources 块中执行此操作:
private static <T, E extends Exception> T configured(T resource, ThrowingConsumer<? super T, E> configuration) throws E {
configuration.accept(resource);
return resource;
}
private interface ThrowingConsumer<T, E extends Exception> {
void accept(T value) throws E;
}
并像这样使用它:
try (Connection conn = null
; Statement statement = configured(conn.createStatement(), stmt -> stmt.setMaxRows(maxRows))
; ResultSet rs = statement.executeQuery(request)) {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.